file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0x3C6Cf487E97c655E264780444b4eC0e2E45D24BB/sources/eigenlayer/interfaces/IStrategy.sol
Minimal interface for an `Strategy` contract. Layr Labs, Inc. Custom `Strategy` implementations may expand extensively on this interface./
interface IStrategy { function deposit(IERC20 token, uint256 amount) external returns (uint256); function withdraw(address depositor, IERC20 token, uint256 amountShares) external; function sharesToUnderlying(uint256 amountShares) external returns (uint256); function underlyingToShares(uint256 amountUnderlying) external returns (uint256); function userUnderlying(address user) external returns (uint256); function sharesToUnderlyingView(uint256 amountShares) external view returns (uint256); function underlyingToSharesView(uint256 amountUnderlying) external view returns (uint256); function userUnderlyingView(address user) external view returns (uint256); function underlyingToken() external view returns (IERC20); function totalShares() external view returns (uint256); function explanation() external view returns (string memory); function shares(address user) external view returns (uint256); pragma solidity ^0.8.9; }
2,982,149
pragma solidity ^0.4.24; contract Owned { /// 'owner' is the only address that can call a function with /// this modifier address public owner; address internal newOwner; ///@notice The constructor assigns the message sender to be 'owner' constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } event updateOwner(address _oldOwner, address _newOwner); ///change the owner function changeOwner(address _newOwner) public onlyOwner returns(bool) { require(owner != _newOwner); newOwner = _newOwner; return true; } /// accept the ownership function acceptNewOwner() public returns(bool) { require(msg.sender == newOwner); emit updateOwner(owner, newOwner); owner = newOwner; return true; } } contract SafeMath { function safeMul(uint a, uint b) pure internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) pure internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) pure internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } contract ERC20Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// user tokens mapping (address => uint256) public balances; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant public returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant public returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract DateTime { /* * Date and Time utilities for ethereum contracts * */ struct _DateTime { uint16 year; uint8 month; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) internal pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) internal pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) internal pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } } function getYear(uint timestamp) internal pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) internal pure returns (uint8) { return parseTimestamp(timestamp).month; } } contract CUSEexerciseContract is Owned,SafeMath,DateTime { /// @dev name of CUSEexec contract string public name = "CUSE_Exercise_Option"; /// @dev decimal of CUSE uint256 decimals = 18; /// @dev token holder address public CUSEaddr = 0x6081dEd2d0a57fC4b63765B182D8773E72327fE2; address constant public USEaddr = 0xd9485499499d66B175Cf5ED54c0a19f1a6Bcb61A; address public tokenHolder = 0x89Ead717c9DC15a222926221897c68F9486E7229; address public officialAddress = 0x41eFD65d4f101ff729D93e7a2b7F9e22f9033332; /// @dev exercise price of Each Month mapping (uint => mapping(uint => uint)) public eachExercisePrice; constructor (uint[] _year, uint[] _month, uint[] _exercisePrice) public { require (_year.length == _month.length); require (_month.length == _exercisePrice.length); for (uint i=0; i<_month.length; i++) { eachExercisePrice[_year[i]][_month[i]] = _exercisePrice[i]; } } function () public payable { address _user = msg.sender; uint _value = msg.value; require(exerciseCUSE(_user, _value) == true); } /// @dev internal function: exercise option of CUSE function exerciseCUSE(address _user, uint _ether) internal returns (bool) { /// @dev get CUSE price uint _exercisePrice = getPrice(); /// @dev get CUSE of msg.sender uint _CUSE = ERC20Token(CUSEaddr).balanceOf(_user); // ETH user send (uint _use, uint _refoundETH) = calcUSE(_CUSE, _ether, _exercisePrice); // do exercise require (ERC20Token(CUSEaddr).transferFrom(_user, officialAddress, _use) == true); require (ERC20Token(USEaddr).transferFrom(tokenHolder, _user, _use) == true); // refound ETH needRefoundETH(_user, _refoundETH); officialAddress.transfer(safeSub(_ether, _refoundETH)); return true; } /// @dev get exercise price function getPrice() internal view returns(uint) { uint _year = getYear(now); uint _month = getMonth(now); return eachExercisePrice[_year][_month]; } /// @dev Calculate USE value function calcUSE(uint _cuse, uint _ether, uint _exercisePrice) internal pure returns (uint _use, uint _refoundETH) { uint _amount = _ether / _exercisePrice; require (_amount > 0); require (safeMul(_amount, _exercisePrice) <= _ether); // Check Whether msg.sender Have Enough CUSE if (safeMul(_amount, 10**18) <= _cuse) { _use = safeMul(_amount, 10**18); _refoundETH = 0; } else { _use = _cuse; _refoundETH = safeMul(safeSub(_amount, _use/(10**18)), _exercisePrice); } } function needRefoundETH(address _user, uint _refoundETH) internal { if (_refoundETH > 0) { _user.transfer(_refoundETH); } } /// @dev Change Exercise Price function changeExerciseprice(uint[] _year, uint[] _month, uint[] _exercisePrice) public onlyOwner { require (_year.length == _month.length); require (_month.length == _exercisePrice.length); for (uint i=0; i<_month.length; i++) { eachExercisePrice[_year[i]][_month[i]] = _exercisePrice[i]; } } function changeCUSEaddress(address _cuseAddr) public onlyOwner { CUSEaddr = _cuseAddr; } /// @dev Change token holder function changeTokenHolder(address _tokenHolder) public onlyOwner { tokenHolder = _tokenHolder; } /// @dev Change Official Address If Necessary function changeOfficialAddressIfNecessary(address _officialAddress) public onlyOwner { officialAddress = _officialAddress; } }
Calculate USE value Check Whether msg.sender Have Enough CUSE
function calcUSE(uint _cuse, uint _ether, uint _exercisePrice) internal pure returns (uint _use, uint _refoundETH) { uint _amount = _ether / _exercisePrice; require (_amount > 0); require (safeMul(_amount, _exercisePrice) <= _ether); if (safeMul(_amount, 10**18) <= _cuse) { _use = safeMul(_amount, 10**18); _refoundETH = 0; _use = _cuse; _refoundETH = safeMul(safeSub(_amount, _use/(10**18)), _exercisePrice); } }
6,992,363
./full_match/1/0x12165d21BE89AE08E16B1a23be8DF41349169D4B/sources/contracts/templates/NFTCollection.sol
Internal function without any checks for performing the ownership transfer
function _transferOwnership(address newOwner) internal { address previousOwner = _deploymentConfig.owner; _revokeRole(ADMIN_ROLE, previousOwner); _revokeRole(DEFAULT_ADMIN_ROLE, previousOwner); _deploymentConfig.owner = newOwner; _grantRole(ADMIN_ROLE, newOwner); _grantRole(DEFAULT_ADMIN_ROLE, newOwner); emit OwnershipTransferred(previousOwner, newOwner); }
3,087,751
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import '@openzeppelin/contracts/utils/EnumerableSet.sol'; import "./uniswapV2/interfaces/IUniswapV2Router02.sol"; import "./uniswapV2/interfaces/IWETH.sol"; import "./PremiaBondingCurve.sol"; /// @author Premia /// @title A contract receiving all protocol fees, swapping them for eth, and using eth to purchase premia on the bonding curve contract PremiaMaker is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; // UniswapRouter contracts which can be used to swap tokens EnumerableSet.AddressSet private _whitelistedRouters; // The premia token IERC20 public premia; // The premia bonding curve PremiaBondingCurve public premiaBondingCurve; // The premia staking contract (xPremia) address public premiaStaking; // The treasury address which will receive a portion of the protocol fees address public treasury; // The percentage of protocol fees the treasury will get (in basis points) uint256 public treasuryFee = 2e3; // 20% uint256 private constant _inverseBasisPoint = 1e4; // Set a custom swap path for a token mapping(address=>address[]) public customPath; //////////// // Events // //////////// event Converted(address indexed account, address indexed router, address indexed token, uint256 tokenAmount, uint256 premiaAmount); ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @param _premia The premia token // @param _premiaBondingCurve The premia bonding curve // @param _premiaStaking The premia staking contract (xPremia) // @param _treasury The treasury address which will receive a portion of the protocol fees constructor(IERC20 _premia, address _premiaStaking, address _treasury) { premia = _premia; premiaStaking = _premiaStaking; treasury = _treasury; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// receive() external payable {} /////////// // Admin // /////////// /// @notice Set a custom swap path for a token /// @param _token The token /// @param _path The swap path function setCustomPath(address _token, address[] memory _path) external onlyOwner { customPath[_token] = _path; } /// @notice Set a new treasury fee /// @param _fee New fee function setTreasuryFee(uint256 _fee) external onlyOwner { require(_fee <= _inverseBasisPoint); treasuryFee = _fee; } /// @notice Set premia bonding curve contract /// @param _premiaBondingCurve PremiaBondingCurve contract function setPremiaBondingCurve(PremiaBondingCurve _premiaBondingCurve) external onlyOwner { premiaBondingCurve = _premiaBondingCurve; } /// @notice Add UniswapRouters to the whitelist so that they can be used to swap tokens. /// @param _addr The addresses to add to the whitelist function addWhitelistedRouter(address[] memory _addr) external onlyOwner { for (uint256 i=0; i < _addr.length; i++) { _whitelistedRouters.add(_addr[i]); } } /// @notice Remove UniswapRouters from the whitelist so that they cannot be used to swap tokens. /// @param _addr The addresses to remove the whitelist function removeWhitelistedRouter(address[] memory _addr) external onlyOwner { for (uint256 i=0; i < _addr.length; i++) { _whitelistedRouters.remove(_addr[i]); } } ////////////////////////// /// @notice Get the list of whitelisted routers /// @return The list of whitelisted routers function getWhitelistedRouters() external view returns(address[] memory) { uint256 length = _whitelistedRouters.length(); address[] memory result = new address[](length); for (uint256 i=0; i < length; i++) { result[i] = _whitelistedRouters.at(i); } return result; } /// @notice Convert tokens into ETH, use ETH to purchase Premia on the bonding curve, and send Premia to PremiaStaking contract /// @param _router The UniswapRouter contract to use to perform the swap (Must be whitelisted) /// @param _token The token to swap to premia function convert(IUniswapV2Router02 _router, address _token) public { require(address(premiaBondingCurve) != address(0), "Premia bonding curve not set"); require(_whitelistedRouters.contains(address(_router)), "Router not whitelisted"); IERC20 token = IERC20(_token); uint256 amount = token.balanceOf(address(this)); uint256 fee = amount.mul(treasuryFee).div(_inverseBasisPoint); uint256 amountMinusFee = amount.sub(fee); token.safeTransfer(treasury, fee); if (amountMinusFee == 0) return; token.safeIncreaseAllowance(address(_router), amountMinusFee); address weth = _router.WETH(); uint256 premiaAmount; if (_token != address(premia)) { if (_token != weth) { address[] memory path = customPath[_token]; if (path.length == 0) { path = new address[](2); path[0] = _token; path[1] = weth; } _router.swapExactTokensForETH( amountMinusFee, 0, path, address(this), block.timestamp.add(60) ); } else { IWETH(weth).withdraw(amountMinusFee); } premiaAmount = premiaBondingCurve.buyTokenWithExactEthAmount{value: address(this).balance}(0, premiaStaking); } else { premiaAmount = amountMinusFee; premia.safeTransfer(premiaStaking, premiaAmount); // Just for the event _router = IUniswapV2Router02(0); } emit Converted(msg.sender, address(_router), _token, amountMinusFee, premiaAmount); } }
Set premia bonding curve contract _premiaBondingCurve PremiaBondingCurve contract
function setPremiaBondingCurve(PremiaBondingCurve _premiaBondingCurve) external onlyOwner { premiaBondingCurve = _premiaBondingCurve; }
6,369,121
// SPDX-License-Identifier: MIT // 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 <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../lib/ABDKMath64x64.sol"; import "../interfaces/IAssimilator.sol"; import "../interfaces/IOracle.sol"; contract NzdsToUsdAssimilator is IAssimilator { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; using SafeMath for uint256; IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IOracle private constant oracle = IOracle(0x3977CFc9e4f29C184D4675f4EB8e0013236e5f3e); IERC20 private constant nzds = IERC20(0xDa446fAd08277B4D2591536F204E018f32B6831c); // solhint-disable-next-line constructor() {} function getRate() public view override returns (uint256) { (, int256 price, , , ) = oracle.latestRoundData(); return uint256(price); } // takes raw nzds amount, transfers it in, calculates corresponding numeraire amount and returns it function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) { bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), _amount); require(_transferSuccess, "Curve/nzds-transfer-from-failed"); uint256 _balance = nzds.balanceOf(address(this)); uint256 _rate = getRate(); balance_ = ((_balance * _rate) / 1e8).divu(1e6); amount_ = ((_amount * _rate) / 1e8).divu(1e6); } // takes raw nzds amount, transfers it in, calculates corresponding numeraire amount and returns it function intakeRaw(uint256 _amount) external override returns (int128 amount_) { bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), _amount); require(_transferSuccess, "Curve/nzds-transfer-from-failed"); uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(1e6); } // takes a numeraire amount, calculates the raw amount of nzds, transfers it in and returns the corresponding raw amount function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(1e6) * 1e8) / _rate; bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), amount_); require(_transferSuccess, "Curve/nzds-transfer-from-failed"); } // takes a numeraire amount, calculates the raw amount of nzds, transfers it in and returns the corresponding raw amount function intakeNumeraireLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr, int128 _amount ) external override returns (uint256 amount_) { uint256 _nzdsBal = nzds.balanceOf(_addr); if (_nzdsBal <= 0) return 0; // 1e6 _nzdsBal = _nzdsBal.mul(1e18).div(_baseWeight); // 1e6 uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in 1e6 uint256 _rate = _usdcBal.mul(1e6).div(_nzdsBal); amount_ = (_amount.mulu(1e6) * 1e6) / _rate; bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), amount_); require(_transferSuccess, "Curve/nzds-transfer-failed"); } // takes a raw amount of nzds and transfers it out, returns numeraire value of the raw amount function outputRawAndGetBalance(address _dst, uint256 _amount) external override returns (int128 amount_, int128 balance_) { uint256 _rate = getRate(); uint256 _nzdsAmount = ((_amount) * _rate) / 1e8; bool _transferSuccess = nzds.transfer(_dst, _nzdsAmount); require(_transferSuccess, "Curve/nzds-transfer-failed"); uint256 _balance = nzds.balanceOf(address(this)); amount_ = _nzdsAmount.divu(1e6); balance_ = ((_balance * _rate) / 1e8).divu(1e6); } // takes a raw amount of nzds and transfers it out, returns numeraire value of the raw amount function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) { uint256 _rate = getRate(); uint256 _nzdsAmount = (_amount * _rate) / 1e8; bool _transferSuccess = nzds.transfer(_dst, _nzdsAmount); require(_transferSuccess, "Curve/nzds-transfer-failed"); amount_ = _nzdsAmount.divu(1e6); } // takes a numeraire value of nzds, figures out the raw amount, transfers raw amount out, and returns raw amount function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(1e6) * 1e8) / _rate; bool _transferSuccess = nzds.transfer(_dst, amount_); require(_transferSuccess, "Curve/nzds-transfer-failed"); } // takes a numeraire amount and returns the raw amount function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(1e6) * 1e8) / _rate; } function viewRawAmountLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr, int128 _amount ) external view override returns (uint256 amount_) { uint256 _nzdsBal = nzds.balanceOf(_addr); if (_nzdsBal <= 0) return 0; // 1e6 _nzdsBal = _nzdsBal.mul(1e18).div(_baseWeight); // 1e6 uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in 1e6 uint256 _rate = _usdcBal.mul(1e6).div(_nzdsBal); amount_ = (_amount.mulu(1e6) * 1e6) / _rate; } // takes a raw amount and returns the numeraire amount function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) { uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(1e6); } // views the numeraire value of the current balance of the reserve, in this case nzds function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) { uint256 _rate = getRate(); uint256 _balance = nzds.balanceOf(_addr); if (_balance <= 0) return ABDKMath64x64.fromUInt(0); balance_ = ((_balance * _rate) / 1e8).divu(1e6); } // views the numeraire value of the current balance of the reserve, in this case nzds function viewNumeraireAmountAndBalance(address _addr, uint256 _amount) external view override returns (int128 amount_, int128 balance_) { uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(1e6); uint256 _balance = nzds.balanceOf(_addr); balance_ = ((_balance * _rate) / 1e8).divu(1e6); } // views the numeraire value of the current balance of the reserve, in this case nzds // instead of calculating with chainlink's "rate" it'll be determined by the existing // token ratio // Mainly to protect LP from losing function viewNumeraireBalanceLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr ) external view override returns (int128 balance_) { uint256 _nzdsBal = nzds.balanceOf(_addr); if (_nzdsBal <= 0) return ABDKMath64x64.fromUInt(0); uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in 1e6 uint256 _rate = _usdcBal.mul(1e18).div(_nzdsBal.mul(1e18).div(_baseWeight)); balance_ = ((_nzdsBal * _rate) / 1e6).divu(1e18); } }
takes a raw amount of nzds and transfers it out, returns numeraire value of the raw amount
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) { uint256 _rate = getRate(); uint256 _nzdsAmount = (_amount * _rate) / 1e8; bool _transferSuccess = nzds.transfer(_dst, _nzdsAmount); require(_transferSuccess, "Curve/nzds-transfer-failed"); amount_ = _nzdsAmount.divu(1e6); }
12,659,187
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: Booster interface Booster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function poolInfo(uint256) external view returns(address,address,address,address,address, bool); // deposit lp tokens and stake function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool); // deposit all lp tokens and stake function depositAll(uint256 _pid, bool _stake) external returns(bool); // withdraw lp tokens function withdraw(uint256 _pid, uint256 _amount) external returns(bool); // withdraw all lp tokens function withdrawAll(uint256 _pid) external returns(bool); // claim crv + extra rewards function earmarkRewards(uint256 _pid) external returns(bool); // claim rewards on stash (msg.sender == stash) function claimRewards(uint256 _pid, address _gauge) external returns(bool); // delegate address votes on dao (needs to be voteDelegate) function vote(uint256 _voteId, address _votingAddress, bool _support) external returns(bool); function voteGaugeWeight(address[] calldata _gauge, uint256[] calldata _weight ) external returns(bool); } // Part: ICurveFi interface ICurveFi { function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount ) external payable; // crv.finance: Curve.fi Factory USD Metapool v2 function add_liquidity( address pool, uint256[4] calldata amounts, uint256 min_mint_amount ) external; function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function balances(int128) external view returns (uint256); function get_virtual_price() external view returns (uint256); } // Part: IERC20Metadata interface IERC20Metadata { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // Part: IStakedAave interface IStakedAave { function COOLDOWN_SECONDS() external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); function getTotalRewardsBalance(address) external view returns (uint256); function stakerRewardsToClaim(address) external view returns (uint256); function stakersCooldowns(address) external view returns (uint256); function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; } // Part: Math /** * @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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/Address /** * @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"); } /** * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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) { 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; } } // Part: Rewards interface Rewards{ function pid() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function extraRewardsLength() external view returns (uint256); function extraRewards(uint256) external view returns (address); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewardToken() external view returns (address); function rewards(address) external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function stakingToken() external view returns (address); function stake(uint256) external returns (bool); function stakeAll() external returns (bool); function stakeFor(address, uint256) external returns (bool); function withdraw(uint256 amount, bool claim) external returns (bool); function withdrawAll(bool claim) external returns (bool); function withdrawAndUnwrap(uint256 amount, bool claim) external returns(bool); function withdrawAllAndUnwrap(bool claim) external; function getReward() external returns(bool); function getReward(address _account, bool _claimExtras) external returns(bool); function donate(uint256 _amount) external returns(bool); } // Part: Uni interface Uni { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); /* Uniswap V3 */ struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput( ExactInputParams calldata params ) external payable returns (uint256 amountOut); function quoteExactInput( bytes calldata path, uint256 amountIn ) external view returns (uint256 amountOut); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.5"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: ConvexStable abstract contract ConvexStable is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant voter = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); address public constant booster = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address public constant usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); address public constant usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // address public constant quoter = address(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6); // address public constant uniswapv3 = address(0xE592427A0AEce92De3Edee1F18E0157C05861564); address public constant uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant sushiswap = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); uint256 public constant DENOMINATOR = 10000; bool public isClaimRewards; bool public isClaimExtras; uint256 public id; address public rewardContract; address public curve; address[] public dex; uint256 public keepCRV; constructor(address _vault) public BaseStrategy(_vault) { minReportDelay = 12 hours; maxReportDelay = 3 days; profitFactor = 1000; debtThreshold = 1e24; keepCRV = 1000; } function _approveBasic() internal { want.approve(booster, 0); want.approve(booster, type(uint256).max); IERC20(dai).safeApprove(curve, 0); IERC20(dai).safeApprove(curve, type(uint256).max); IERC20(usdc).safeApprove(curve, 0); IERC20(usdc).safeApprove(curve, type(uint256).max); IERC20(usdt).safeApprove(curve, 0); IERC20(usdt).safeApprove(curve, type(uint256).max); } function _approveDex() internal virtual { IERC20(crv).approve(dex[0], 0); IERC20(crv).approve(dex[0], type(uint256).max); IERC20(cvx).approve(dex[1], 0); IERC20(cvx).approve(dex[1], type(uint256).max); } function approveAll() external onlyAuthorized { _approveBasic(); _approveDex(); } function setKeepCRV(uint256 _keepCRV) external onlyAuthorized { keepCRV = _keepCRV; } function switchDex(uint256 _id, address _dex) external onlyAuthorized { dex[_id] = _dex; _approveDex(); } function setIsClaimRewards(bool _isClaimRewards) external onlyAuthorized { isClaimRewards = _isClaimRewards; } function setIsClaimExtras(bool _isClaimExtras) external onlyAuthorized { isClaimExtras = _isClaimExtras; } function withdrawToConvexDepositTokens() external onlyAuthorized { uint256 staked = Rewards(rewardContract).balanceOf(address(this)); Rewards(rewardContract).withdraw(staked, isClaimRewards); } function name() external view override returns (string memory) { return string(abi.encodePacked("Convex", IERC20Metadata(address(want)).symbol())); } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { return Rewards(rewardContract).balanceOf(address(this)); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) return; uint256 _want = want.balanceOf(address(this)); if (_want > 0) { Booster(booster).deposit(id, _want, true); } } function _withdrawSome(uint256 _amount) internal returns (uint256) { _amount = Math.min(_amount, balanceOfPool()); uint _before = balanceOfWant(); Rewards(rewardContract).withdrawAndUnwrap(_amount, false); return balanceOfWant().sub(_before); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _balance = balanceOfWant(); if (_balance < _amountNeeded) { _liquidatedAmount = _withdrawSome(_amountNeeded.sub(_balance)); _liquidatedAmount = _liquidatedAmount.add(_balance); _loss = _amountNeeded.sub(_liquidatedAmount); // this should be 0. o/w there must be an error } else { _liquidatedAmount = _amountNeeded; } } function prepareMigration(address _newStrategy) internal override { Rewards(rewardContract).withdrawAllAndUnwrap(isClaimRewards); _migrateRewards(_newStrategy); } function _migrateRewards(address _newStrategy) internal virtual { IERC20(crv).safeTransfer(_newStrategy, IERC20(crv).balanceOf(address(this))); IERC20(cvx).safeTransfer(_newStrategy, IERC20(cvx).balanceOf(address(this))); } function _adjustCRV(uint256 _crv) internal returns (uint256) { uint256 _keepCRV = _crv.mul(keepCRV).div(DENOMINATOR); if (_keepCRV > 0) IERC20(crv).safeTransfer(voter, _keepCRV); return _crv.sub(_keepCRV); } function _claimableBasicInETH() internal view returns (uint256) { uint256 _crv = Rewards(rewardContract).earned(address(this)); // calculations pulled directly from CVX's contract for minting CVX per CRV claimed uint256 totalCliffs = 1000; uint256 maxSupply = 1e8 * 1e18; // 100m uint256 reductionPerCliff = 1e5 * 1e18; // 100k uint256 supply = IERC20(cvx).totalSupply(); uint256 _cvx; uint256 cliff = supply.div(reductionPerCliff); // mint if below total cliffs if (cliff < totalCliffs) { // for reduction% take inverse of current cliff uint256 reduction = totalCliffs.sub(cliff); // reduce _cvx = _crv.mul(reduction).div(totalCliffs); // supply cap check uint256 amtTillMax = maxSupply.sub(supply); if (_cvx > amtTillMax) { _cvx = amtTillMax; } } uint256 crvValue; if (_crv > 0) { address[] memory path = new address[](2); path[0] = crv; path[1] = weth; uint256[] memory crvSwap = Uni(dex[0]).getAmountsOut(_crv, path); crvValue = crvSwap[1]; } uint256 cvxValue; if (_cvx > 0) { address[] memory path = new address[](2); path[0] = cvx; path[1] = weth; uint256[] memory cvxSwap = Uni(dex[1]).getAmountsOut(_cvx, path); cvxValue = cvxSwap[1]; } return crvValue.add(cvxValue); } function _claimableInETH() internal virtual view returns (uint256 _claimable) { _claimable = _claimableBasicInETH(); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function harvestTrigger(uint256 callCost) public override view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); if (params.activation == 0) return false; if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; uint256 total = estimatedTotalAssets(); if (total.add(debtThreshold) < params.totalDebt) return true; return (profitFactor.mul(callCost) < _claimableInETH()); } } // File: aave.sol contract Strategy is ConvexStable { address public constant stkaave = address(0x4da27a545c0c5B758a6BA100e3a049001de870f5); address public constant aave = address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); address[] public pathTarget; constructor(address _vault) public ConvexStable(_vault) { curve = address(0xDeBF20617708857ebe4F679508E7b7863a8A8EeE); id = 24; isClaimRewards = true; // default is true, turn off in emergency isClaimExtras = true; // add this if there are extra rewards (address _lp,,,address _reward,,) = Booster(booster).poolInfo(id); require(_lp == address(want), "constructor: incorrect lp token"); rewardContract = _reward; _approveBasic(); pathTarget = new address[](3); _setPathTarget(0, 0); // crv path target _setPathTarget(1, 0); // cvx path target _setPathTarget(2, 0); // aave path target dex = new address[](3); dex[0] = sushiswap; // crv dex[1] = sushiswap; // cvx dex[2] = sushiswap; // aave _approveDex(); } // >>> approve other rewards on dex function _approveDex() internal override { super._approveDex(); IERC20(aave).approve(dex[2], 0); IERC20(aave).approve(dex[2], type(uint256).max); } // >>> include other rewards function _migrateRewards(address _newStrategy) internal override { super._migrateRewards(_newStrategy); claim(); IERC20(stkaave).safeTransfer(_newStrategy, IERC20(stkaave).balanceOf(address(this))); IERC20(aave).safeTransfer(_newStrategy, IERC20(aave).balanceOf(address(this))); } // >>> include all other rewards in eth besides _claimableBasicInETH() function _claimableInETH() internal override view returns (uint256 _claimable) { _claimable = super._claimableInETH(); uint256 _aave = IERC20(aave).balanceOf(address(this)); if (_aave > 0) { address[] memory path = new address[](2); path[0] = aave; path[1] = weth; uint256[] memory swap = Uni(dex[2]).getAmountsOut(_aave, path); _claimable = _claimable.add(swap[1]); } } function _setPathTarget(uint _tokenId, uint _id) internal { if (_id == 0) { pathTarget[_tokenId] = dai; } else if (_id == 1) { pathTarget[_tokenId] = usdc; } else { pathTarget[_tokenId] = usdt; } } function setPathTarget(uint _tokenId, uint _id) external onlyAuthorized { _setPathTarget(_tokenId, _id); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint before = balanceOfWant(); Rewards(rewardContract).getReward(address(this), isClaimExtras); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { _crv = _adjustCRV(_crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = pathTarget[0]; Uni(dex[0]).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now); } uint256 _cvx = IERC20(cvx).balanceOf(address(this)); if (_cvx > 0) { address[] memory path = new address[](3); path[0] = cvx; path[1] = weth; path[2] = pathTarget[1]; Uni(dex[1]).swapExactTokensForTokens(_cvx, uint256(0), path, address(this), now); } uint256 _stkaave = IERC20(stkaave).balanceOf(address(this)); if (_stkaave > 0) { (bool isCooldown, uint cooldown, uint cooldown_seconds, uint unstake_window) = _checkCooldown(); if (isCooldown) { claim(); // claim aave rewards IStakedAave(stkaave).redeem(address(this), _stkaave); } if (cooldown == 0 || block.timestamp > cooldown_seconds.add(unstake_window)) { IStakedAave(stkaave).cooldown(); } } uint256 _aave = IERC20(aave).balanceOf(address(this)); if (_aave > 0) { address[] memory path = new address[](3); path[0] = aave; path[1] = weth; path[2] = pathTarget[2]; Uni(dex[2]).swapExactTokensForTokens(_aave, uint256(0), path, address(this), now); } uint256 _dai = IERC20(dai).balanceOf(address(this)); uint256 _usdc = IERC20(usdc).balanceOf(address(this)); uint256 _usdt = IERC20(usdt).balanceOf(address(this)); if (_dai > 0 || _usdc > 0 || _usdt > 0) { ICurveFi(curve).add_liquidity([_dai, _usdc, _usdt], 0, true); } _profit = want.balanceOf(address(this)).sub(before); uint _total = estimatedTotalAssets(); uint _debt = vault.strategies(address(this)).totalDebt; if(_total < _debt) { _loss = _debt - _total; _profit = 0; } if (_debtOutstanding > 0) { _withdrawSome(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, balanceOfWant().sub(_profit)); } } function claim() public { // claim aave rewards IStakedAave(stkaave).claimRewards(address(this), type(uint256).max); } function _checkCooldown() public view returns ( bool isCooldown, uint cooldown, uint cooldown_seconds, uint unstake_window ) { cooldown = IStakedAave(stkaave).stakersCooldowns(address(this)); cooldown_seconds = IStakedAave(stkaave).COOLDOWN_SECONDS(); unstake_window = IStakedAave(stkaave).UNSTAKE_WINDOW(); cooldown_seconds = cooldown.add(cooldown_seconds); isCooldown = ( cooldown != 0 && block.timestamp > cooldown_seconds && block.timestamp <= cooldown_seconds.add(unstake_window) ); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](3); protected[0] = crv; protected[1] = cvx; protected[2] = aave; return protected; } }
calculations pulled directly from CVX's contract for minting CVX per CRV claimed mint if below total cliffs for reduction% take inverse of current cliff reduce supply cap check
function _claimableBasicInETH() internal view returns (uint256) { uint256 _crv = Rewards(rewardContract).earned(address(this)); uint256 totalCliffs = 1000; uint256 supply = IERC20(cvx).totalSupply(); uint256 _cvx; uint256 cliff = supply.div(reductionPerCliff); if (cliff < totalCliffs) { uint256 reduction = totalCliffs.sub(cliff); _cvx = _crv.mul(reduction).div(totalCliffs); uint256 amtTillMax = maxSupply.sub(supply); if (_cvx > amtTillMax) { _cvx = amtTillMax; } } uint256 crvValue; if (_crv > 0) { address[] memory path = new address[](2); path[0] = crv; path[1] = weth; uint256[] memory crvSwap = Uni(dex[0]).getAmountsOut(_crv, path); crvValue = crvSwap[1]; } uint256 cvxValue; if (_cvx > 0) { address[] memory path = new address[](2); path[0] = cvx; path[1] = weth; uint256[] memory cvxSwap = Uni(dex[1]).getAmountsOut(_cvx, path); cvxValue = cvxSwap[1]; } return crvValue.add(cvxValue); }
128,393
// File: contracts/interfaces/SIInterface.sol interface SIInterface { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); } // File: contracts/interfaces/marketHandlerDataStorageInterface.sol pragma solidity 0.6.12; interface marketHandlerDataStorageInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/interfaces/marketManagerInterface.sol pragma solidity 0.6.12; interface marketManagerInterface { function setBreakerTable(address _target, bool _status) external returns (bool); function getCircuitBreaker() external view returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory); function handlerRegister(uint256 handlerID, address tokenHandlerAddr) external returns (bool); function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256); function liquidationApplyInterestHandlers(address payable userAddr, uint256 callerID) external returns (uint256, uint256, uint256, uint256, uint256); function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256); function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function getTokenHandlersLength() external view returns (uint256); function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256); function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256); function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256); function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256); function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (bool); function updateRewardParams(address payable userAddr) external returns (bool); function interestUpdateReward() external returns (bool); function getGlobalRewardInfo() external view returns (uint256, uint256, uint256); function setOracleProxy(address oracleProxyAddr) external returns (bool); function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool); function ownerRewardTransfer(uint256 _amount) external returns (bool); } // File: contracts/interfaces/interestModelInterface.sol pragma solidity 0.6.12; interface interestModelInterface { function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256); function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256); function getSIRandBIR(address handlerDataStorageAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256); } // File: contracts/interfaces/tokenInterface.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external view returns (bool); function transferFrom(address from, address to, uint256 value) external ; } // File: contracts/interfaces/marketSIHandlerDataStorageInterface.sol pragma solidity 0.6.12; interface marketSIHandlerDataStorageInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool); function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool); function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256); function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool); function getBetaRate() external view returns (uint256); function setBetaRate(uint256 _betaRate) external returns (bool); } // File: contracts/marketHandler/tokenSI.sol pragma solidity 0.6.12; /** * @title Bifi tokenSI Contract * @notice Service incentive logic * @author Bifi */ contract tokenSI is SIInterface { event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID); address payable owner; uint256 handlerID; string tokenName; uint256 constant unifiedPoint = 10 ** 18; uint256 unifiedTokenDecimal; uint256 underlyingTokenDecimal; marketManagerInterface marketManager; interestModelInterface interestModelInstance; marketHandlerDataStorageInterface handlerDataStorage; marketSIHandlerDataStorageInterface SIHandlerDataStorage; IERC20 erc20Instance; struct MarketRewardInfo { uint256 rewardLane; uint256 rewardLaneUpdateAt; uint256 rewardPerBlock; } struct UserRewardInfo { uint256 rewardLane; uint256 rewardLaneUpdateAt; uint256 rewardAmount; } modifier onlyMarketManager { address msgSender = msg.sender; require((msgSender == address(marketManager)) || (msgSender == owner), "onlyMarketManager function"); _; } modifier onlyOwner { require(msg.sender == address(owner), "onlyOwner function"); _; } /** * @dev Transfer ownership * @param _owner the address of the new owner * @return true (TODO: validate results) */ function ownershipTransfer(address _owner) onlyOwner external returns (bool) { owner = address(uint160(_owner)); return true; } /** * @dev Set circuitBreak to freeze/unfreeze all handlers by owne * @param _emergency The status of the circuit breaker * @return true (TODO: validate results) */ function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool) { SIHandlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Set circuitBreak to freeze/unfreeze all handlers by marketManager * @param _emergency The status of the circuit breaker * @return true (TODO: validate results) */ function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool) { SIHandlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Update the amount of rewards per block * @param _rewardPerBlock The amount of the reward amount per block * @return true (TODO: validate results) */ function updateRewardPerBlockLogic(uint256 _rewardPerBlock) onlyMarketManager external override returns (bool) { return SIHandlerDataStorage.updateRewardPerBlockStorage(_rewardPerBlock); } /** * @dev Update the reward lane (the acculumated sum of the reward unit per block) of the market and user * @param userAddr The address of user * @return Whether or not this process has succeeded */ function updateRewardLane(address payable userAddr) external override returns (bool) { MarketRewardInfo memory market; UserRewardInfo memory user; marketSIHandlerDataStorageInterface _SIHandlerDataStorage = SIHandlerDataStorage; (market.rewardLane, market.rewardLaneUpdateAt, market.rewardPerBlock, user.rewardLane, user.rewardLaneUpdateAt, user.rewardAmount) = _SIHandlerDataStorage.getRewardInfo(userAddr); uint256 currentBlockNum = block.number; uint256 depositTotalAmount; uint256 borrowTotalAmount; uint256 depositUserAmount; uint256 borrowUserAmount; (depositTotalAmount, borrowTotalAmount, depositUserAmount, borrowUserAmount) = handlerDataStorage.getAmount(userAddr); /* Unless the reward lane of the market is updated at the current block */ if (market.rewardLaneUpdateAt < currentBlockNum) { uint256 _delta = sub(currentBlockNum, market.rewardLaneUpdateAt); uint256 betaRateBaseTotalAmount = _calcBetaBaseAmount(_SIHandlerDataStorage.getBetaRate(), depositTotalAmount, borrowTotalAmount); if (betaRateBaseTotalAmount != 0) { /* update the reward lane */ market.rewardLane = add(market.rewardLane, _calcRewardLaneDistance(_delta, market.rewardPerBlock, betaRateBaseTotalAmount)); } _SIHandlerDataStorage.setMarketRewardInfo(market.rewardLane, currentBlockNum, market.rewardPerBlock); } /* Unless the reward lane of the user is updated at the current block */ if (user.rewardLaneUpdateAt < currentBlockNum) { uint256 betaRateBaseUserAmount = _calcBetaBaseAmount(_SIHandlerDataStorage.getBetaRate(), depositUserAmount, borrowUserAmount); if (betaRateBaseUserAmount != 0) { user.rewardAmount = add(user.rewardAmount, unifiedMul(betaRateBaseUserAmount, sub(market.rewardLane, user.rewardLane))); } _SIHandlerDataStorage.setUserRewardInfo(userAddr, market.rewardLane, currentBlockNum, user.rewardAmount); return true; } return false; } /** * @dev Calculates the reward lane distance (for delta blocks) based on the given parameters. * @param _delta The blockNumber difference * @param _rewardPerBlock The amount of reward per block * @param _total The total amount of betaRate * @return The reward lane distance */ function _calcRewardLaneDistance(uint256 _delta, uint256 _rewardPerBlock, uint256 _total) internal pure returns (uint256) { return mul(_delta, unifiedDiv(_rewardPerBlock, _total)); } /** * @dev Get the total amount of betaRate * @return The total amount of betaRate */ function getBetaRateBaseTotalAmount() external view override returns (uint256) { return _getBetaRateBaseTotalAmount(); } /** * @dev Get the total amount of betaRate * @return The total amount of betaRate */ function _getBetaRateBaseTotalAmount() internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = handlerDataStorage.getHandlerAmount(); return _calcBetaBaseAmount(SIHandlerDataStorage.getBetaRate(), depositTotalAmount, borrowTotalAmount); } /** * @dev Calculate the rewards given to the user by using the beta score (external). * betaRateBaseAmount = (depositAmount * betaRate) + ((1 - betaRate) * borrowAmount) * @param userAddr The address of user * @return The beta score of the user */ function getBetaRateBaseUserAmount(address payable userAddr) external view override returns (uint256) { return _getBetaRateBaseUserAmount(userAddr); } /** * @dev Calculate the rewards given to the user by using the beta score (internal) * betaRateBaseAmount = (depositAmount * betaRate) + ((1 - betaRate) * borrowAmount) * @param userAddr The address of user * @return The beta score of the user */ function _getBetaRateBaseUserAmount(address payable userAddr) internal view returns (uint256) { uint256 depositUserAmount; uint256 borrowUserAmount; (depositUserAmount, borrowUserAmount) = handlerDataStorage.getUserAmount(userAddr); return _calcBetaBaseAmount(SIHandlerDataStorage.getBetaRate(), depositUserAmount, borrowUserAmount); } function _calcBetaBaseAmount(uint256 _beta, uint256 _depositAmount, uint256 _borrowAmount) internal pure returns (uint256) { return add(unifiedMul(_depositAmount, _beta), unifiedMul(_borrowAmount, sub(unifiedPoint, _beta))); } /** * @dev Claim rewards for the user (external) * @param userAddr The address of user * @return The amount of user reward */ function claimRewardAmountUser(address payable userAddr) onlyMarketManager external returns (uint256) { return _claimRewardAmountUser(userAddr); } /** * @dev Claim rewards for the user (internal) * @param userAddr The address of user * @return The amount of user reward */ function _claimRewardAmountUser(address payable userAddr) internal returns (uint256) { UserRewardInfo memory user; uint256 currentBlockNum = block.number; (user.rewardLane, user.rewardLaneUpdateAt, user.rewardAmount) = SIHandlerDataStorage.getUserRewardInfo(userAddr); /* reset the user reward */ SIHandlerDataStorage.setUserRewardInfo(userAddr, user.rewardLane, currentBlockNum, 0); return user.rewardAmount; } /** * @dev Get the reward parameters of the market * @return (rewardLane, rewardLaneUpdateAt, rewardPerBlock) */ function getMarketRewardInfo() external view override returns (uint256, uint256, uint256) { return SIHandlerDataStorage.getMarketRewardInfo(); } /** * @dev Get reward parameters for the user * @return (uint256,uint256,uint256) (rewardLane, rewardLaneUpdateAt, rewardAmount) */ function getUserRewardInfo(address payable userAddr) external view override returns (uint256, uint256, uint256) { return SIHandlerDataStorage.getUserRewardInfo(userAddr); } /** * @dev Get the rate of beta (beta-score) * @return The rate of beta (beta-score) */ function getBetaRate() external view returns (uint256) { return SIHandlerDataStorage.getBetaRate(); } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "sub overflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "div by zero"); } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return _mod(a, b, "mod by zero"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require((c / a) == b, "mul overflow"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "unified div by zero"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "unified mul by zero"); } function signedAdd(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require(((b >= 0) && (c >= a)) || ((b < 0) && (c < a)), "SignedSafeMath: addition overflow"); return c; } function signedSub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require(((b >= 0) && (c <= a)) || ((b < 0) && (c > a)), "SignedSafeMath: subtraction overflow"); return c; } } // File: contracts/truffleKit/LinkSi.sol contract LinkSI is tokenSI { constructor() tokenSI() public {} }
Calculates the reward lane distance (for delta blocks) based on the given parameters. _delta The blockNumber difference _rewardPerBlock The amount of reward per block _total The total amount of betaRate return The reward lane distance/
function _calcRewardLaneDistance(uint256 _delta, uint256 _rewardPerBlock, uint256 _total) internal pure returns (uint256) { return mul(_delta, unifiedDiv(_rewardPerBlock, _total)); }
5,937,300
./partial_match/1/0x6894DD96d242bA513AD99836B7778dBF43b82F3f/sources/AnyswapV6ERC20.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); }
4,127,197
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "../storage/SettingsNamespace.sol"; import "../mixins/OwnerMixin.sol"; contract SettingsModule is SettingsNamespace, OwnerMixin { /* MUTATIVE FUNCTIONS */ function setASettingValue(uint newSettingValue) public onlyOwner { _settingsStorage().aSettingValue = newSettingValue; } /* VIEW FUNCTIONS */ function getASettingValue() public view returns (uint) { return _settingsStorage().aSettingValue; } }
MUTATIVE FUNCTIONS /
function setASettingValue(uint newSettingValue) public onlyOwner { _settingsStorage().aSettingValue = newSettingValue; }
6,442,124
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // =============================== veFXS ============================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Original idea and credit: // Curve Finance's veCRV // https://resources.curve.fi/faq/vote-locking-boost // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/VotingEscrow.vy // This is a Solidity version converted from Vyper by the Frax team // Almost all of the logic / algorithms are the Curve team's // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian //@notice Votes have a weight depending on time, so that users are // committed to the future of (whatever they are voting for) //@dev Vote weight decays linearly over time. Lock time cannot be // more than `MAXTIME` (3 years). // Voting escrow to have time-weighted votes // Votes have a weight depending on time, so that users are committed // to the future of (whatever they are voting for). // The weight in this implementation is linear, and lock cannot be more than maxtime: // w ^ // 1 + / // | / // | / // | / // |/ // 0 +--------+------> time // maxtime (3 years?) import "../Utils/Math.sol"; import "../Utils/TransferHelper.sol"; import "../Governance/Comp.sol"; import "../Utils/StringHelpers.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // import "../Frax/Frax.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // Inheritance import "../Utils/Owned.sol"; import "../Utils/Pausable.sol"; // # Interface for checking whether address belongs to a whitelisted // # type of a smart wallet. // # When new types are added - the whole contract is changed // # The check() method is modifying to be able to use caching // # for individual wallet addresses interface SmartWalletChecker { function check(address addr) external returns (bool); } contract veToken is ReentrancyGuard{ using SafeMath for uint256; using SafeERC20 for IERC20; // We cannot really do block numbers per se b/c slope is per time, not per block // and per block could be fairly bad b/c Ethereum changes blocktimes. // What we can do is to extrapolate ***At functions struct Point { int128 bias; int128 slope; // dweight / dt uint256 ts; uint256 blk; // block } struct LockedBalance { int128 amount; uint256 end; } /* ========== STATE VARIABLES ========== */ address public token; // FXS uint256 public supply; // veFXS uint256 public epoch; mapping (address => LockedBalance) public locked; Point[100000000000000000000000000000] public point_history; // epoch (total 10 ** 29) -> unsigned point mapping (address => Point[1000000000]) public user_point_history; // 10 ** 9 epoch mapping (address => uint256) public user_point_epoch; mapping (uint256 => int128) public slope_changes; // time -> signed slope change // Aragon's view methods for address public controller; bool public transfersEnabled; // veFXS token related string public name; string public symbol; string public version; uint256 public decimals; // Checker for whitelisted (smart contract) wallets which are allowed to deposit // The goal is to prevent tokenizing the escrow address public future_smart_wallet_checker; address public smart_wallet_checker; address public admin; // Can and will be a smart contract address public future_admin; int128 public constant DEPOSIT_FOR_TYPE = 0; int128 public constant CREATE_LOCK_TYPE = 1; int128 public constant INCREASE_LOCK_AMOUNT = 2; int128 public constant INCREASE_UNLOCK_TIME = 3; address public constant ZERO_ADDRESS = address(0); uint256 public constant WEEK = 7 * 86400; // all future times are rounded by week uint256 public constant MAXTIME = 3 * 365 * 86400; // 3 years uint256 public constant MULTIPLIER = 10 ** 18; /* ========== MODIFIERS ========== */ modifier onlyAdmin { require(msg.sender == admin, "You are not the admin"); _; } /* ========== CONSTRUCTOR ========== */ // token_addr: address, _name: String[64], _symbol: String[32], _version: String[32] /** * @notice Contract constructor * @param token_addr `ERC20CRV` token address * @param _name Token name * @param _symbol Token symbol * @param _version Contract version - required for Aragon compatibility */ constructor ( address token_addr, string memory _name, string memory _symbol, string memory _version ) { admin = msg.sender; token = token_addr; point_history[0].blk = block.number; point_history[0].ts = block.timestamp; controller = msg.sender; transfersEnabled = true; // todo: debug // uint256 _decimals = IERC20Metadata(token_addr).decimals(); uint256 _decimals = 18; assert(_decimals <= 255); decimals = _decimals; name = _name; symbol = _symbol; version = _version; } /* ========== VIEWS ========== */ // Constant structs not allowed yet, so this will have to do function EMPTY_POINT_FACTORY() internal view returns (Point memory){ return Point({ bias: 0, slope: 0, ts: 0, blk: 0 }); } // Constant structs not allowed yet, so this will have to do function EMPTY_LOCKED_BALANCE_FACTORY() internal view returns (LockedBalance memory){ return LockedBalance({ amount: 0, end: 0 }); } /** * @notice Get the most recently recorded rate of voting power decrease for `addr` * @param addr Address of the user wallet * @return Value of the slope */ function get_last_user_slope(address addr) external view returns (int128) { uint256 uepoch = user_point_epoch[addr]; return user_point_history[addr][uepoch].slope; } /** * @notice Get the timestamp for checkpoint `_idx` for `_addr` * @param _addr User wallet address * @param _idx User epoch number * @return Epoch time of the checkpoint */ function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256) { return user_point_history[_addr][_idx].ts; } /** * @notice Get timestamp when `_addr`'s lock finishes * @param _addr User wallet * @return Epoch time of the lock end */ function locked__end(address _addr) external view returns (uint256) { return locked[_addr].end; } /** * @notice Get the current voting power for `msg.sender` at the specified timestamp * @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility * @param addr User wallet address * @param _t Epoch time to return voting power at * @return User voting power */ function balanceOf(address addr, uint256 _t) internal view returns (uint256) { uint256 _epoch = user_point_epoch[addr]; if (_epoch == 0) { return 0; } else { Point memory last_point = user_point_history[addr][_epoch]; last_point.bias -= last_point.slope * (int128(uint128(_t)) - int128(uint128(last_point.ts))); if (last_point.bias < 0) { last_point.bias = 0; } return uint256(int256(last_point.bias)); } } /** * @notice Get the current voting power for `msg.sender` at the current timestamp * @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility * @param addr User wallet address * @return User voting power */ function balanceOf(address addr) public view returns (uint256) { return balanceOf(addr, block.timestamp); } /** * @notice Measure voting power of `addr` at block height `_block` * @dev Adheres to MiniMe `balanceOfAt` interface: https://github.com/Giveth/minime * @param addr User's wallet address * @param _block Block to calculate the voting power at * @return Voting power */ function balanceOfAt(address addr, uint256 _block) external view returns (uint256) { // Copying and pasting totalSupply code because Vyper cannot pass by // reference yet require(_block <= block.number); // Binary search uint256 _min = 0; uint256 _max = user_point_epoch[addr]; // Will be always enough for 128-bit numbers for(uint i = 0; i < 128; i++){ if (_min >= _max) { break; } uint256 _mid = (_min + _max + 1) / 2; if (user_point_history[addr][_mid].blk <= _block) { _min = _mid; } else { _max = _mid - 1; } } Point memory upoint = user_point_history[addr][_min]; uint256 max_epoch = epoch; uint256 _epoch = find_block_epoch(_block, max_epoch); Point memory point_0 = point_history[_epoch]; uint256 d_block = 0; uint256 d_t = 0; if (_epoch < max_epoch) { Point memory point_1 = point_history[_epoch + 1]; d_block = point_1.blk - point_0.blk; d_t = point_1.ts - point_0.ts; } else { d_block = block.number - point_0.blk; d_t = block.timestamp - point_0.ts; } uint256 block_time = point_0.ts; if (d_block != 0) { block_time += d_t * (_block - point_0.blk) / d_block; } upoint.bias -= upoint.slope * (int128(uint128(block_time)) - int128(uint128(upoint.ts))); if (upoint.bias >= 0) { return uint256(int256(upoint.bias)); } else { return 0; } } /** * @notice Calculate total voting power at the specified timestamp * @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility * @return Total voting power */ function totalSupply(uint256 t) internal view returns (uint256) { uint256 _epoch = epoch; Point memory last_point = point_history[_epoch]; return supply_at(last_point, t); } /** * @notice Calculate total voting power at the current timestamp * @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility * @return Total voting power */ function totalSupply() public view returns (uint256) { return totalSupply(block.timestamp); } /** * @notice Calculate total voting power at some point in the past * @param _block Block to calculate the total voting power at * @return Total voting power at `_block` */ function totalSupplyAt(uint256 _block) external view returns (uint256) { require(_block <= block.number); uint256 _epoch = epoch; uint256 target_epoch = find_block_epoch(_block, _epoch); Point memory point = point_history[target_epoch]; uint256 dt = 0; if (target_epoch < _epoch) { Point memory point_next = point_history[target_epoch + 1]; if (point.blk != point_next.blk) { dt = ((_block - point.blk) * (point_next.ts - point.ts)) / (point_next.blk - point.blk); } } else { if (point.blk != block.number) { dt = ((_block - point.blk) * (block.timestamp - point.ts)) / (block.number - point.blk); } } // Now dt contains info on how far are we beyond point return supply_at(point, point.ts + dt); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Check if the call is from a whitelisted smart contract, revert if not * @param addr Address to be checked */ function assert_not_contract(address addr) internal { if (addr != tx.origin) { address checker = smart_wallet_checker; if (checker != ZERO_ADDRESS){ if (SmartWalletChecker(checker).check(addr)){ return; } } revert("Smart contract depositors not allowed"); } } /** * @notice Record global and per-user data to checkpoint * @param addr User's wallet address. No user checkpoint if 0x0 * @param old_locked Previous locked amount / end lock time for the user * @param new_locked New locked amount / end lock time for the user */ function _checkpoint( address addr, LockedBalance memory old_locked, LockedBalance memory new_locked ) internal { Point memory u_old = EMPTY_POINT_FACTORY(); Point memory u_new = EMPTY_POINT_FACTORY(); int128 old_dslope = 0; int128 new_dslope = 0; uint256 _epoch = epoch; if (addr != ZERO_ADDRESS){ // Calculate slopes and biases // Kept at zero when they have to // 追加质押 if ((old_locked.end > block.timestamp) && (old_locked.amount > 0)){ u_old.slope = old_locked.amount / int128(uint128(MAXTIME)); u_old.bias = u_old.slope * (int128(uint128(old_locked.end)) - int128(uint128(block.timestamp))); } // 新建质押 if ((new_locked.end > block.timestamp) && (new_locked.amount > 0)){ // 时间衰减斜率 / 3 u_new.slope = new_locked.amount / int128(uint128(MAXTIME)); // 当前额外数 / 3 u_new.bias = u_new.slope * (int128(uint128(new_locked.end)) - int128(uint128(block.timestamp))); } // Read values of scheduled changes in the slope // old_locked.end can be in the past and in the future // new_locked.end can ONLY by in the FUTURE unless everything expired: than zeros // 新建为0 old_dslope = slope_changes[old_locked.end]; // 新建 if (new_locked.end != 0) { if (new_locked.end == old_locked.end) { new_dslope = old_dslope; } else { // 新建为0 new_dslope = slope_changes[new_locked.end]; } } } Point memory last_point = Point({ bias: 0, slope: 0, ts: block.timestamp, blk: block.number }); if (_epoch > 0) { last_point = point_history[_epoch]; } uint256 last_checkpoint = last_point.ts; // initial_last_point is used for extrapolation to calculate block number // (approximately, for *At methods) and save them // as we cannot figure that out exactly from inside the contract Point memory initial_last_point = last_point; uint256 block_slope = 0; // dblock/dt if (block.timestamp > last_point.ts) { // b / s * 10 ** 18 block_slope = MULTIPLIER * (block.number - last_point.blk) / (block.timestamp - last_point.ts); } // If last point is already recorded in this block, slope=0 // But that's ok b/c we know the block in such case // Go over weeks to fill history and calculate what the current point is // 上次记录ts -> 满周的ts uint256 t_i = (last_checkpoint / WEEK) * WEEK; for(uint i = 0; i < 255; i++){ // Hopefully it won't happen that this won't get used in 4 years! // If it does, users will be able to withdraw but vote weight will be broken t_i += WEEK; int128 d_slope = 0; if (t_i > block.timestamp) { // 更新到当前ts t_i = block.timestamp; } else { // 当前ts之前(包括当前ts)的满周ts d_slope = slope_changes[t_i]; } last_point.bias -= last_point.slope * (int128(uint128(t_i)) - int128(uint128(last_checkpoint))); last_point.slope += d_slope; if (last_point.bias < 0) { last_point.bias = 0; // This can happen } if (last_point.slope < 0) { last_point.slope = 0; // This cannot happen - just in case } last_checkpoint = t_i; last_point.ts = t_i; last_point.blk = initial_last_point.blk + block_slope * (t_i - initial_last_point.ts) / MULTIPLIER; _epoch += 1; if (t_i == block.timestamp){ last_point.blk = block.number; break; } else { point_history[_epoch] = last_point; } } epoch = _epoch; // Now point_history is filled until t=now if (addr != ZERO_ADDRESS) { // If last point was in this block, the slope change has been applied already // But in such case we have 0 slope(s) last_point.slope += (u_new.slope - u_old.slope); last_point.bias += (u_new.bias - u_old.bias); if (last_point.slope < 0) { last_point.slope = 0; } if (last_point.bias < 0) { last_point.bias = 0; } } // Record the changed point into history point_history[_epoch] = last_point; if (addr != ZERO_ADDRESS) { // Schedule the slope changes (slope is going down) // We subtract new_user_slope from [new_locked.end] // and add old_user_slope to [old_locked.end] if (old_locked.end > block.timestamp) { // old_dslope was <something> - u_old.slope, so we cancel that old_dslope += u_old.slope; if (new_locked.end == old_locked.end) { old_dslope -= u_new.slope; // It was a new deposit, not extension } slope_changes[old_locked.end] = old_dslope; } if (new_locked.end > block.timestamp) { if (new_locked.end > old_locked.end) { new_dslope -= u_new.slope; // old slope disappeared at this point slope_changes[new_locked.end] = new_dslope; } // else: we recorded it already in old_dslope } // Now handle user history // Second function needed for 'stack too deep' issues _checkpoint_part_two(addr, u_new.bias, u_new.slope); } } /** * @notice Needed for 'stack too deep' issues in _checkpoint() * @param addr User's wallet address. No user checkpoint if 0x0 * @param _bias from unew * @param _slope from unew */ function _checkpoint_part_two(address addr, int128 _bias, int128 _slope) internal { uint256 user_epoch = user_point_epoch[addr] + 1; user_point_epoch[addr] = user_epoch; user_point_history[addr][user_epoch] = Point({ bias: _bias, slope: _slope, ts: block.timestamp, blk: block.number }); } /** * @notice Deposit and lock tokens for a user * @param _addr User's wallet address * @param _value Amount to deposit * @param unlock_time New time when to unlock the tokens, or 0 if unchanged * @param locked_balance Previous locked amount / timestamp */ function _deposit_for( address _addr, uint256 _value, uint256 unlock_time, LockedBalance memory locked_balance, int128 _type ) internal { LockedBalance memory _locked = locked_balance; uint256 supply_before = supply; supply = supply_before + _value; LockedBalance memory old_locked = _locked; // Adding to existing lock, or if a lock is expired - creating a new one _locked.amount += int128(uint128(_value)); if (unlock_time != 0) { _locked.end = unlock_time; } locked[_addr] = _locked; // Possibilities: // Both old_locked.end could be current or expired (>/< block.timestamp) // value == 0 (extend lock) or value > 0 (add to lock or extend lock) // _locked.end > block.timestamp (always) _checkpoint(_addr, old_locked, _locked); if (_value != 0) { assert(IERC20(token).transferFrom(_addr, address(this), _value)); } emit Deposit(_addr, _value, _locked.end, _type, block.timestamp); emit Supply(supply_before, supply_before + _value); } // The following ERC20/minime-compatible methods are not real balanceOf and supply! // They measure the weights for the purpose of voting, so they don't represent // real coins. /** * @notice Binary search to estimate timestamp for block number * @param _block Block to find * @param max_epoch Don't go beyond this epoch * @return Approximate timestamp for block */ function find_block_epoch(uint256 _block, uint256 max_epoch) internal view returns (uint256) { // Binary search uint256 _min = 0; uint256 _max = max_epoch; // Will be always enough for 128-bit numbers for (uint i = 0; i < 128; i++){ if (_min >= _max) { break; } uint256 _mid = (_min + _max + 1) / 2; if (point_history[_mid].blk <= _block) { _min = _mid; } else { _max = _mid - 1; } } return _min; } /** * @notice Calculate total voting power at some point in the past * @param point The point (bias/slope) to start search from * @param t Time to calculate the total voting power at * @return Total voting power at that time */ function supply_at(Point memory point, uint256 t) internal view returns (uint256) { Point memory last_point = point; uint256 t_i = (last_point.ts / WEEK) * WEEK; for(uint i = 0; i < 255; i++){ t_i += WEEK; int128 d_slope = 0; if (t_i > t) { t_i = t; } else { d_slope = slope_changes[t_i]; } last_point.bias -= last_point.slope * (int128(uint128(t_i)) - int128(uint128(last_point.ts))); if (t_i == t) { break; } last_point.slope += d_slope; last_point.ts = t_i; } if (last_point.bias < 0) { last_point.bias = 0; } return uint256(int256(last_point.bias)); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Record global data to checkpoint */ function checkpoint(address _addr) external { _checkpoint(ZERO_ADDRESS, EMPTY_LOCKED_BALANCE_FACTORY(), EMPTY_LOCKED_BALANCE_FACTORY()); } /** * @notice Deposit and lock tokens for a user * @dev Anyone (even a smart contract) can deposit for someone else, but cannot extend their locktime and deposit for a brand new user * @param _addr User's wallet address * @param _value Amount to add to user's lock */ function deposit_for(address _addr, uint256 _value) external nonReentrant { LockedBalance memory _locked = locked[_addr]; require (_value > 0, "need non-zero value"); require (_locked.amount > 0, "No existing lock found"); require (_locked.end > block.timestamp, "Cannot add to expired lock. Withdraw"); _deposit_for(_addr, _value, 0, locked[_addr], DEPOSIT_FOR_TYPE); } function getUnlockTime(uint unlock_time, bool isInput) external view returns(uint) { if (isInput) { return unlock_time; } return (unlock_time / WEEK) * WEEK; } /** * @notice Deposit `_value` tokens for `msg.sender` and lock until `_unlock_time` * @param _value Amount to deposit * @param _unlock_time Epoch time when tokens unlock, rounded down to whole weeks */ function create_lock(uint256 _value, uint256 _unlock_time) external nonReentrant { assert_not_contract(msg.sender); uint256 unlock_time = (_unlock_time / WEEK) * WEEK ; // Locktime is rounded down to weeks LockedBalance memory _locked = locked[msg.sender]; require (_value > 0, "need non-zero value"); require (_locked.amount == 0, "Withdraw old tokens first"); require (unlock_time > block.timestamp, "Can only lock until time in the future"); require (unlock_time <= block.timestamp + MAXTIME, "Voting lock can be 3 years max"); _deposit_for(msg.sender, _value, unlock_time, _locked, CREATE_LOCK_TYPE); } /** * @notice Deposit `_value` additional tokens for `msg.sender` without modifying the unlock time * @param _value Amount of tokens to deposit and add to the lock */ function increase_amount(uint256 _value) external nonReentrant { assert_not_contract(msg.sender); LockedBalance memory _locked = locked[msg.sender]; require(_value > 0, "need non-zero value"); require(_locked.amount > 0, "No existing lock found"); require(_locked.end > block.timestamp, "Cannot add to expired lock. Withdraw"); _deposit_for(msg.sender, _value, 0, _locked, INCREASE_LOCK_AMOUNT); } /** * @notice Extend the unlock time for `msg.sender` to `_unlock_time` * @param _unlock_time New epoch time for unlocking */ function increase_unlock_time(uint256 _unlock_time) external nonReentrant { assert_not_contract(msg.sender); LockedBalance memory _locked = locked[msg.sender]; uint256 unlock_time = (_unlock_time / WEEK) * WEEK; // Locktime is rounded down to weeks require(_locked.end > block.timestamp, "Lock expired"); require(_locked.amount > 0, "Nothing is locked"); require(unlock_time > _locked.end, "Can only increase lock duration"); require(unlock_time <= block.timestamp + MAXTIME, "Voting lock can be 3 years max"); _deposit_for(msg.sender, 0, unlock_time, _locked, INCREASE_UNLOCK_TIME); } /** * @notice Withdraw all tokens for `msg.sender`ime` * @dev Only possible if the lock has expired */ function withdraw() external nonReentrant { LockedBalance memory _locked = locked[msg.sender]; require(block.timestamp >= _locked.end, "The lock didn't expire"); uint256 value = uint256(int256(_locked.amount)); LockedBalance memory old_locked = _locked; _locked.end = 0; _locked.amount = 0; locked[msg.sender] = _locked; uint256 supply_before = supply; supply = supply_before - value; // old_locked can have either expired <= timestamp or zero end // _locked has only 0 end // Both can have >= 0 amount _checkpoint(msg.sender, old_locked, _locked); require(IERC20(token).transfer(msg.sender, value)); emit Withdraw(msg.sender, value, block.timestamp); emit Supply(supply_before, supply_before - value); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @notice Transfer ownership of VotingEscrow contract to `addr` * @param addr Address to have ownership transferred to */ function commit_transfer_ownership(address addr) external onlyAdmin { future_admin = addr; emit CommitOwnership(addr); } /** * @notice Apply ownership transfer */ function apply_transfer_ownership() external onlyAdmin { address _admin = future_admin; assert (_admin != ZERO_ADDRESS); // dev: admin not set admin = _admin; emit ApplyOwnership(_admin); } /** * @notice Set an external contract to check for approved smart contract wallets * @param addr Address of Smart contract checker */ function commit_smart_wallet_checker(address addr) external onlyAdmin { future_smart_wallet_checker = addr; } /** * @notice Apply setting external contract to check approved smart contract wallets */ function apply_smart_wallet_checker() external onlyAdmin { smart_wallet_checker = future_smart_wallet_checker; } /** * @notice Dummy method for compatibility with Aragon * @dev Dummy method required for Aragon compatibility */ function changeController(address _newController) external { require(msg.sender == controller); controller = _newController; } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyAdmin { // Admin cannot withdraw the staking token from the contract unless currently migrating // if(!migrationsOn){ // require(tokenAddress != address(FXS), "Not in migration"); // Only Governance / Timelock can trigger a migration // } // Only the owner address can ever receive the recovery withdrawal IERC20(tokenAddress).transfer(admin, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); event CommitOwnership(address admin); event ApplyOwnership(address admin); event Deposit(address indexed provider, uint256 value, uint256 indexed locktime, int128 _type, uint256 ts); event Withdraw(address indexed provider, uint256 value, uint256 ts); event Supply(uint256 prevSupply, uint256 supply); }
Get the most recently recorded rate of voting power decrease for `addr` addr Address of the user wallet return Value of the slope/
function get_last_user_slope(address addr) external view returns (int128) { uint256 uepoch = user_point_epoch[addr]; return user_point_history[addr][uepoch].slope; }
1,062,028
pragma solidity 0.4.23; /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint256) { uint c = a / b; return c; } function safeSub(uint a, uint b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint256) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title Stoppable * @dev Base contract which allows children to implement final irreversible stop mechanism. */ contract Stoppable is Pausable { event Stop(); bool public stopped = false; /** * @dev Modifier to make a function callable only when the contract is not stopped. */ modifier whenNotStopped() { require(!stopped); _; } /** * @dev Modifier to make a function callable only when the contract is stopped. */ modifier whenStopped() { require(stopped); _; } /** * @dev called by the owner to pause, triggers stopped state */ function stop() public onlyOwner whenNotStopped { stopped = true; emit Stop(); } } /** * @title Eth2Phone Escrow Contract * @dev Contract allows to send ether through verifier (owner of contract). * * Only verifier can initiate withdrawal to recipient&#39;s address. * Verifier cannot choose recipient&#39;s address without * transit private key generated by sender. * * Sender is responsible to provide transit private key * to recipient off-chain. * * Recepient signs address to receive with transit private key and * provides signed address to verification server. * (See VerifyTransferSignature method for details.) * * Verifier verifies off-chain the recipient in accordance with verification * conditions (e.g., phone ownership via SMS authentication) and initiates * withdrawal to the address provided by recipient. * (See withdraw method for details.) * * Verifier charges commission for it&#39;s services. * * Sender is able to cancel transfer if it&#39;s not yet cancelled or withdrawn * by recipient. * (See cancelTransfer method for details.) */ contract e2pEscrow is Stoppable, SafeMath { // fixed amount of wei accrued to verifier with each transfer uint public commissionFee; // verifier can withdraw this amount from smart-contract uint public commissionToWithdraw; // in wei // verifier&#39;s address address public verifier; /* * EVENTS */ event LogDeposit( address indexed sender, address indexed transitAddress, uint amount, uint commission ); event LogCancel( address indexed sender, address indexed transitAddress ); event LogWithdraw( address indexed sender, address indexed transitAddress, address indexed recipient, uint amount ); event LogWithdrawCommission(uint commissionAmount); event LogChangeFixedCommissionFee( uint oldCommissionFee, uint newCommissionFee ); event LogChangeVerifier( address oldVerifier, address newVerifier ); struct Transfer { address from; uint amount; // in wei } // Mappings of transitAddress => Transfer Struct mapping (address => Transfer) transferDct; /** * @dev Contructor that sets msg.sender as owner (verifier) in Ownable * and sets verifier&#39;s fixed commission fee. * @param _commissionFee uint Verifier&#39;s fixed commission for each transfer */ constructor(uint _commissionFee, address _verifier) public { commissionFee = _commissionFee; verifier = _verifier; } modifier onlyVerifier() { require(msg.sender == verifier); _; } /** * @dev Deposit ether to smart-contract and create transfer. * Transit address is assigned to transfer by sender. * Recipient should sign withrawal address with the transit private key * * @param _transitAddress transit address assigned to transfer. * @return True if success. */ function deposit(address _transitAddress) public whenNotPaused whenNotStopped payable returns(bool) { // can not override existing transfer require(transferDct[_transitAddress].amount == 0); require(msg.value > commissionFee); // saving transfer details transferDct[_transitAddress] = Transfer( msg.sender, safeSub(msg.value, commissionFee)//amount = msg.value - comission ); // accrue verifier&#39;s commission commissionToWithdraw = safeAdd(commissionToWithdraw, commissionFee); // log deposit event emit LogDeposit(msg.sender, _transitAddress, msg.value, commissionFee); return true; } /** * @dev Change verifier&#39;s fixed commission fee. * Only owner can change commision fee. * * @param _newCommissionFee uint New verifier&#39;s fixed commission * @return True if success. */ function changeFixedCommissionFee(uint _newCommissionFee) public whenNotPaused whenNotStopped onlyOwner returns(bool success) { uint oldCommissionFee = commissionFee; commissionFee = _newCommissionFee; emit LogChangeFixedCommissionFee(oldCommissionFee, commissionFee); return true; } /** * @dev Change verifier&#39;s address. * Only owner can change verifier&#39;s address. * * @param _newVerifier address New verifier&#39;s address * @return True if success. */ function changeVerifier(address _newVerifier) public whenNotPaused whenNotStopped onlyOwner returns(bool success) { address oldVerifier = verifier; verifier = _newVerifier; emit LogChangeVerifier(oldVerifier, verifier); return true; } /** * @dev Transfer accrued commission to verifier&#39;s address. * @return True if success. */ function withdrawCommission() public whenNotPaused returns(bool success) { uint commissionToTransfer = commissionToWithdraw; commissionToWithdraw = 0; owner.transfer(commissionToTransfer); // owner is verifier emit LogWithdrawCommission(commissionToTransfer); return true; } /** * @dev Get transfer details. * @param _transitAddress transit address assigned to transfer * @return Transfer details (id, sender, amount) */ function getTransfer(address _transitAddress) public constant returns ( address id, address from, // transfer sender uint amount) // in wei { Transfer memory transfer = transferDct[_transitAddress]; return ( _transitAddress, transfer.from, transfer.amount ); } /** * @dev Cancel transfer and get sent ether back. Only transfer sender can * cancel transfer. * @param _transitAddress transit address assigned to transfer * @return True if success. */ function cancelTransfer(address _transitAddress) public returns (bool success) { Transfer memory transferOrder = transferDct[_transitAddress]; // only sender can cancel transfer; require(msg.sender == transferOrder.from); delete transferDct[_transitAddress]; // transfer ether to recipient&#39;s address msg.sender.transfer(transferOrder.amount); // log cancel event emit LogCancel(msg.sender, _transitAddress); return true; } /** * @dev Verify that address is signed with correct verification private key. * @param _transitAddress transit address assigned to transfer * @param _recipient address Signed address. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return True if signature is correct. */ function verifySignature( address _transitAddress, address _recipient, uint8 _v, bytes32 _r, bytes32 _s) public pure returns(bool success) { bytes32 prefixedHash = keccak256("\x19Ethereum Signed Message:\n32", _recipient); address retAddr = ecrecover(prefixedHash, _v, _r, _s); return retAddr == _transitAddress; } /** * @dev Verify that address is signed with correct private key for * verification public key assigned to transfer. * @param _transitAddress transit address assigned to transfer * @param _recipient address Signed address. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return True if signature is correct. */ function verifyTransferSignature( address _transitAddress, address _recipient, uint8 _v, bytes32 _r, bytes32 _s) public pure returns(bool success) { return (verifySignature(_transitAddress, _recipient, _v, _r, _s)); } /** * @dev Withdraw transfer to recipient&#39;s address if it is correctly signed * with private key for verification public key assigned to transfer. * * @param _transitAddress transit address assigned to transfer * @param _recipient address Signed address. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return True if success. */ function withdraw( address _transitAddress, address _recipient, uint8 _v, bytes32 _r, bytes32 _s ) public onlyVerifier // only through verifier can withdraw transfer; whenNotPaused whenNotStopped returns (bool success) { Transfer memory transferOrder = transferDct[_transitAddress]; // verifying signature require(verifySignature(_transitAddress, _recipient, _v, _r, _s )); delete transferDct[_transitAddress]; // transfer ether to recipient&#39;s address _recipient.transfer(transferOrder.amount); // log withdraw event emit LogWithdraw(transferOrder.from, _transitAddress, _recipient, transferOrder.amount); return true; } // fallback function - do not receive ether by default function() public payable { revert(); } }
Withdraw transfer to recipient&39;s address if it is correctly signed with private key for verification public key assigned to transfer. _transitAddress transit address assigned to transfer _recipient address Signed address. _v ECDSA signature parameter v. _r ECDSA signature parameters r. _s ECDSA signature parameters s. return True if success./ verifying signature transfer ether to recipient&39;s address log withdraw event
function withdraw( address _transitAddress, address _recipient, uint8 _v, bytes32 _r, bytes32 _s ) public whenNotPaused whenNotStopped returns (bool success) { Transfer memory transferOrder = transferDct[_transitAddress]; require(verifySignature(_transitAddress, _recipient, _v, _r, _s )); delete transferDct[_transitAddress]; _recipient.transfer(transferOrder.amount); emit LogWithdraw(transferOrder.from, _transitAddress, _recipient, transferOrder.amount); return true; }
7,852,568
pragma solidity ^0.4.11; // File: @laborx/solidity-shared-lib/contracts/ERC20Interface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Defines an interface for EIP20 token smart contract contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() public view returns (uint8); function totalSupply() public view returns (uint256 supply); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); } // File: contracts/assets/ChronoBankAssetChainableInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankAssetChainableInterface { function assetType() public pure returns (bytes32); function getPreviousAsset() public view returns (ChronoBankAssetChainableInterface); function getNextAsset() public view returns (ChronoBankAssetChainableInterface); function getChainedAssets() public view returns (bytes32[] _types, address[] _assets); function getAssetByType(bytes32 _assetType) public view returns (address); function chainAssets(ChronoBankAssetChainableInterface[] _assets) external returns (bool); function __chainAssetsFromIdx(ChronoBankAssetChainableInterface[] _assets, uint _startFromIdx) external returns (bool); function finalizeAssetChaining() public; } // File: contracts/assets/ChronoBankAssetUtils.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; library ChronoBankAssetUtils { uint constant ASSETS_CHAIN_MAX_LENGTH = 20; function getChainedAssets(ChronoBankAssetChainableInterface _asset) public view returns (bytes32[] _types, address[] _assets) { bytes32[] memory _tempTypes = new bytes32[](ASSETS_CHAIN_MAX_LENGTH); address[] memory _tempAssets = new address[](ASSETS_CHAIN_MAX_LENGTH); ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); uint _counter = 0; do { _tempTypes[_counter] = _next.assetType(); _tempAssets[_counter] = address(_next); _counter += 1; _next = _next.getNextAsset(); } while (address(_next) != 0x0); _types = new bytes32[](_counter); _assets = new address[](_counter); for (uint _assetIdx = 0; _assetIdx < _counter; ++_assetIdx) { _types[_assetIdx] = _tempTypes[_assetIdx]; _assets[_assetIdx] = _tempAssets[_assetIdx]; } } function getAssetByType(ChronoBankAssetChainableInterface _asset, bytes32 _assetType) public view returns (address) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (_next.assetType() == _assetType) { return address(_next); } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function containsAssetInChain(ChronoBankAssetChainableInterface _asset, address _checkAsset) public view returns (bool) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (address(_next) == _checkAsset) { return true; } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function getHeadAsset(ChronoBankAssetChainableInterface _asset) public view returns (ChronoBankAssetChainableInterface) { ChronoBankAssetChainableInterface _head = _asset; ChronoBankAssetChainableInterface _previousAsset; do { _previousAsset = _head.getPreviousAsset(); if (address(_previousAsset) == 0x0) { return _head; } _head = _previousAsset; } while (true); } } // File: @laborx/solidity-eventshistory-lib/contracts/EventsHistorySourceAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title EventsHistory Source Adapter. */ contract EventsHistorySourceAdapter { // It is address of MultiEventsHistory caller assuming we are inside of delegate call. function _self() internal view returns (address) { return msg.sender; } } // File: @laborx/solidity-eventshistory-lib/contracts/MultiEventsHistoryAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title General MultiEventsHistory user. */ contract MultiEventsHistoryAdapter is EventsHistorySourceAdapter { address internal localEventsHistory; event ErrorCode(address indexed self, uint errorCode); function getEventsHistory() public view returns (address) { address _eventsHistory = localEventsHistory; return _eventsHistory != 0x0 ? _eventsHistory : this; } function emitErrorCode(uint _errorCode) public { emit ErrorCode(_self(), _errorCode); } function _setEventsHistory(address _eventsHistory) internal returns (bool) { localEventsHistory = _eventsHistory; return true; } function _emitErrorCode(uint _errorCode) internal returns (uint) { MultiEventsHistoryAdapter(getEventsHistory()).emitErrorCode(_errorCode); return _errorCode; } } // File: contracts/ChronoBankPlatformEmitter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /// @title ChronoBank Platform Emitter. /// /// Contains all the original event emitting function definitions and events. /// In case of new events needed later, additional emitters can be developed. /// All the functions is meant to be called using delegatecall. contract ChronoBankPlatformEmitter is MultiEventsHistoryAdapter { event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference); event Issue(bytes32 indexed symbol, uint value, address indexed by); event Revoke(bytes32 indexed symbol, uint value, address indexed by); event RevokeExternal(bytes32 indexed symbol, uint value, address indexed by, string externalReference); event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol); event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value); event Recovery(address indexed from, address indexed to, address by); function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) public { emit Transfer(_from, _to, _symbol, _value, _reference); } function emitIssue(bytes32 _symbol, uint _value, address _by) public { emit Issue(_symbol, _value, _by); } function emitRevoke(bytes32 _symbol, uint _value, address _by) public { emit Revoke(_symbol, _value, _by); } function emitRevokeExternal(bytes32 _symbol, uint _value, address _by, string _externalReference) public { emit RevokeExternal(_symbol, _value, _by, _externalReference); } function emitOwnershipChange(address _from, address _to, bytes32 _symbol) public { emit OwnershipChange(_from, _to, _symbol); } function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) public { emit Approve(_from, _spender, _symbol, _value); } function emitRecovery(address _from, address _to, address _by) public { emit Recovery(_from, _to, _by); } } // File: contracts/ChronoBankPlatformInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; contract ChronoBankPlatformInterface is ChronoBankPlatformEmitter { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public view returns (bytes32); function symbolsCount() public view returns (uint); function isCreated(bytes32 _symbol) public view returns(bool); function isOwner(address _owner, bytes32 _symbol) public view returns(bool); function owner(bytes32 _symbol) public view returns(address); function setProxy(address _address, bytes32 _symbol) public returns(uint errorCode); function name(bytes32 _symbol) public view returns(string); function totalSupply(bytes32 _symbol) public view returns(uint); function balanceOf(address _holder, bytes32 _symbol) public view returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns(uint); function baseUnit(bytes32 _symbol) public view returns(uint8); function description(bytes32 _symbol) public view returns(string); function isReissuable(bytes32 _symbol) public view returns(bool); function blockNumber(bytes32 _symbol) public view returns (uint); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber) public returns(uint errorCode); function issueAssetWithInitialReceiver(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account) public returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public returns (uint); function revokeAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint); function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool); function isDesignatedAssetManager(address _account, bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns(uint errorCode); } // File: contracts/ChronoBankAssetInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetInterface { function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns(bool); function __process(bytes /*_data*/, address /*_sender*/) public payable { revert("ASSET_PROCESS_NOT_SUPPORTED"); } } // File: contracts/ChronoBankAssetProxy.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ERC20 is ERC20Interface {} contract ChronoBankAsset is ChronoBankAssetInterface {} /// @title ChronoBank Asset Proxy. /// /// Proxy implements ERC20 interface and acts as a gateway to a single platform asset. /// Proxy adds symbol and caller(sender) when forwarding requests to platform. /// Every request that is made by caller first sent to the specific asset implementation /// contract, which then calls back to be forwarded onto platform. /// /// Calls flow: Caller -> /// Proxy.func(...) -> /// Asset.__func(..., Caller.address) -> /// Proxy.__func(..., Caller.address) -> /// Platform.proxyFunc(..., symbol, Caller.address) /// /// Asset implementation contract is mutable, but each user have an option to stick with /// old implementation, through explicit decision made in timely manner, if he doesn't agree /// with new rules. /// Each user have a possibility to upgrade to latest asset contract implementation, without the /// possibility to rollback. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankAssetProxy is ERC20 { /// @dev Supports ChronoBankPlatform ability to return error codes from methods uint constant OK = 1; /// @dev Assigned platform, immutable. ChronoBankPlatform public chronoBankPlatform; /// @dev Assigned symbol, immutable. bytes32 public smbl; /// @dev Assigned name, immutable. string public name; /// @dev Assigned symbol (from ERC20 standard), immutable string public symbol; /// @notice Sets platform address, assigns symbol and name. /// Can be set only once. /// @param _chronoBankPlatform platform contract address. /// @param _symbol assigned symbol. /// @param _name assigned name. /// @return success. function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) public returns (bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @dev Only platform is allowed to call. modifier onlyChronoBankPlatform { if (msg.sender == address(chronoBankPlatform)) { _; } } /// @dev Only current asset owner is allowed to call. modifier onlyAssetOwner { if (chronoBankPlatform.isOwner(msg.sender, smbl)) { _; } } /// @dev Returns asset implementation contract for current caller. /// @return asset implementation contract. function _getAsset() internal view returns (ChronoBankAsset) { return ChronoBankAsset(getVersionFor(msg.sender)); } /// @notice Returns asset total supply. /// @return asset total supply. function totalSupply() public view returns (uint) { return chronoBankPlatform.totalSupply(smbl); } /// @notice Returns asset balance for a particular holder. /// @param _owner holder address. /// @return holder balance. function balanceOf(address _owner) public view returns (uint) { return chronoBankPlatform.balanceOf(_owner, smbl); } /// @notice Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @return holder to spender allowance. function allowance(address _from, address _spender) public view returns (uint) { return chronoBankPlatform.allowance(_from, _spender, smbl); } /// @notice Returns asset decimals. /// @return asset decimals. function decimals() public view returns (uint8) { return chronoBankPlatform.baseUnit(smbl); } /// @notice Transfers asset balance from the caller to specified receiver. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transfer(address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } } /// @notice Transfers asset balance from the caller to specified receiver adding specified comment. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @return success. function transferWithReference(address _to, uint _value, string _reference) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } } /// @notice Resolves asset implementation contract for the caller and forwards there arguments along with /// the caller address. /// @return success. function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /// @notice Performs transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferWithReference( address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /// @notice Performs allowance transfer of asset balance between holders. /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } } /// @notice Performs allowance transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferFromWithReference( address _from, address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /// @notice Sets asset spending allowance for a specified spender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @return success. function approve(address _spender, uint _value) public returns (bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } } /// @notice Performs allowance setting call on the platform by the name of specified sender. /// Can only be called by asset implementation contract assigned to sender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _sender initial caller. /// @return success. function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /// @notice Emits ERC20 Transfer event on this contract. /// Can only be, and, called by assigned platform when asset transfer happens. function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform public { emit Transfer(_from, _to, _value); } /// @notice Emits ERC20 Approval event on this contract. /// Can only be, and, called by assigned platform when asset allowance set happens. function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform public { emit Approval(_from, _spender, _value); } /// @notice Resolves asset implementation contract for the caller and forwards there transaction data, /// along with the value. This allows for proxy interface growth. function () public payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /// @dev Indicates an upgrade freeze-time start, and the next asset implementation contract. event UpgradeProposal(address newVersion); /// @dev Current asset implementation contract address. address latestVersion; /// @dev Proposed next asset implementation contract address. address pendingVersion; /// @dev Upgrade freeze-time start. uint pendingVersionTimestamp; /// @dev Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; /// @dev Asset implementation contract address that user decided to stick with. /// 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /// @dev Only asset implementation contract assigned to sender is allowed to call. modifier onlyAccess(address _sender) { address _versionFor = getVersionFor(_sender); if (msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender) ) { _; } } /// @notice Returns asset implementation contract address assigned to sender. /// @param _sender sender address. /// @return asset implementation contract address. function getVersionFor(address _sender) public view returns (address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /// @notice Returns current asset implementation contract address. /// @return asset implementation contract address. function getLatestVersion() public view returns (address) { return latestVersion; } /// @notice Returns proposed next asset implementation contract address. /// @return asset implementation contract address. function getPendingVersion() public view returns (address) { return pendingVersion; } /// @notice Returns upgrade freeze-time start. /// @return freeze-time start. function getPendingVersionTimestamp() public view returns (uint) { return pendingVersionTimestamp; } /// @notice Propose next asset implementation contract address. /// Can only be called by current asset owner. /// Note: freeze-time should not be applied for the initial setup. /// @param _newVersion asset implementation contract address. /// @return success. function proposeUpgrade(address _newVersion) onlyAssetOwner public returns (bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; emit UpgradeProposal(_newVersion); return true; } /// @notice Cancel the pending upgrade process. /// Can only be called by current asset owner. /// @return success. function purgeUpgrade() public onlyAssetOwner returns (bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Finalize an upgrade process setting new asset implementation contract address. /// Can only be called after an upgrade freeze-time. /// @return success. function commitUpgrade() public returns (bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Disagree with proposed upgrade, and stick with current asset implementation /// until further explicit agreement to upgrade. /// @return success. function optOut() public returns (bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /// @notice Implicitly agree to upgrade to current and future asset implementation upgrades, /// until further explicit disagreement. /// @return success. function optIn() public returns (bool) { delete userOptOutVersion[msg.sender]; return true; } } // File: @laborx/solidity-shared-lib/contracts/Owned.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Owned contract with safe ownership pass. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public contractOwner; address public pendingContractOwner; modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } constructor() public { contractOwner = msg.sender; } /// @notice Prepares ownership pass. /// Can only be called by current owner. /// @param _to address of the next owner. /// @return success. function changeContractOwnership(address _to) public onlyContractOwner returns (bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /// @notice Finalize ownership pass. /// Can only be called by pending owner. /// @return success. function claimContractOwnership() public returns (bool) { if (msg.sender != pendingContractOwner) { return false; } emit OwnershipTransferred(contractOwner, pendingContractOwner); contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) public onlyContractOwner returns (bool) { if (newOwner == 0x0) { return false; } emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @dev Backward compatibility only. /// @param newOwner The address to transfer ownership to. function transferContractOwnership(address newOwner) public returns (bool) { return transferOwnership(newOwner); } /// @notice Withdraw given tokens from contract to owner. /// This method is only allowed for contact owner. function withdrawTokens(address[] tokens) public onlyContractOwner { address _contractOwner = contractOwner; for (uint i = 0; i < tokens.length; i++) { ERC20Interface token = ERC20Interface(tokens[i]); uint balance = token.balanceOf(this); if (balance > 0) { token.transfer(_contractOwner, balance); } } } /// @notice Withdraw ether from contract to owner. /// This method is only allowed for contact owner. function withdrawEther() public onlyContractOwner { uint balance = address(this).balance; if (balance > 0) { contractOwner.transfer(balance); } } /// @notice Transfers ether to another address. /// Allowed only for contract owners. /// @param _to recepient address /// @param _value wei to transfer; must be less or equal to total balance on the contract function transferEther(address _to, uint256 _value) public onlyContractOwner { require(_to != 0x0, "INVALID_ETHER_RECEPIENT_ADDRESS"); if (_value > address(this).balance) { revert("INVALID_VALUE_TO_TRANSFER_ETHER"); } _to.transfer(_value); } } // File: @laborx/solidity-storage-lib/contracts/Storage.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract Manager { function isAllowed(address _actor, bytes32 _role) public view returns (bool); function hasAccess(address _actor) public view returns (bool); } contract Storage is Owned { struct Crate { mapping(bytes32 => uint) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(bytes32 => int) ints; mapping(bytes32 => uint8) uint8s; mapping(bytes32 => bytes32) bytes32s; mapping(bytes32 => AddressUInt8) addressUInt8s; mapping(bytes32 => string) strings; } struct AddressUInt8 { address _address; uint8 _uint8; } mapping(bytes32 => Crate) internal crates; Manager public manager; modifier onlyAllowed(bytes32 _role) { if (!(msg.sender == address(this) || manager.isAllowed(msg.sender, _role))) { revert("STORAGE_FAILED_TO_ACCESS_PROTECTED_FUNCTION"); } _; } function setManager(Manager _manager) external onlyContractOwner returns (bool) { manager = _manager; return true; } function setUInt(bytes32 _crate, bytes32 _key, uint _value) public onlyAllowed(_crate) { _setUInt(_crate, _key, _value); } function _setUInt(bytes32 _crate, bytes32 _key, uint _value) internal { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) public view returns (uint) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) public onlyAllowed(_crate) { _setAddress(_crate, _key, _value); } function _setAddress(bytes32 _crate, bytes32 _key, address _value) internal { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) public view returns (address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) public onlyAllowed(_crate) { _setBool(_crate, _key, _value); } function _setBool(bytes32 _crate, bytes32 _key, bool _value) internal { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) public view returns (bool) { return crates[_crate].bools[_key]; } function setInt(bytes32 _crate, bytes32 _key, int _value) public onlyAllowed(_crate) { _setInt(_crate, _key, _value); } function _setInt(bytes32 _crate, bytes32 _key, int _value) internal { crates[_crate].ints[_key] = _value; } function getInt(bytes32 _crate, bytes32 _key) public view returns (int) { return crates[_crate].ints[_key]; } function setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) public onlyAllowed(_crate) { _setUInt8(_crate, _key, _value); } function _setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) internal { crates[_crate].uint8s[_key] = _value; } function getUInt8(bytes32 _crate, bytes32 _key) public view returns (uint8) { return crates[_crate].uint8s[_key]; } function setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) public onlyAllowed(_crate) { _setBytes32(_crate, _key, _value); } function _setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) internal { crates[_crate].bytes32s[_key] = _value; } function getBytes32(bytes32 _crate, bytes32 _key) public view returns (bytes32) { return crates[_crate].bytes32s[_key]; } function setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) public onlyAllowed(_crate) { _setAddressUInt8(_crate, _key, _value, _value2); } function _setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) internal { crates[_crate].addressUInt8s[_key] = AddressUInt8(_value, _value2); } function getAddressUInt8(bytes32 _crate, bytes32 _key) public view returns (address, uint8) { return (crates[_crate].addressUInt8s[_key]._address, crates[_crate].addressUInt8s[_key]._uint8); } function setString(bytes32 _crate, bytes32 _key, string _value) public onlyAllowed(_crate) { _setString(_crate, _key, _value); } function _setString(bytes32 _crate, bytes32 _key, string _value) internal { crates[_crate].strings[_key] = _value; } function getString(bytes32 _crate, bytes32 _key) public view returns (string) { return crates[_crate].strings[_key]; } } // File: @laborx/solidity-storage-lib/contracts/StorageInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; library StorageInterface { struct Config { Storage store; bytes32 crate; } struct UInt { bytes32 id; } struct UInt8 { bytes32 id; } struct Int { bytes32 id; } struct Address { bytes32 id; } struct Bool { bytes32 id; } struct Bytes32 { bytes32 id; } struct String { bytes32 id; } struct Mapping { bytes32 id; } struct StringMapping { String id; } struct UIntBoolMapping { Bool innerMapping; } struct UIntUIntMapping { Mapping innerMapping; } struct UIntBytes32Mapping { Mapping innerMapping; } struct UIntAddressMapping { Mapping innerMapping; } struct UIntEnumMapping { Mapping innerMapping; } struct AddressBoolMapping { Mapping innerMapping; } struct AddressUInt8Mapping { bytes32 id; } struct AddressUIntMapping { Mapping innerMapping; } struct AddressBytes32Mapping { Mapping innerMapping; } struct AddressAddressMapping { Mapping innerMapping; } struct Bytes32UIntMapping { Mapping innerMapping; } struct Bytes32UInt8Mapping { UInt8 innerMapping; } struct Bytes32BoolMapping { Bool innerMapping; } struct Bytes32Bytes32Mapping { Mapping innerMapping; } struct Bytes32AddressMapping { Mapping innerMapping; } struct Bytes32UIntBoolMapping { Bool innerMapping; } struct AddressAddressUInt8Mapping { Mapping innerMapping; } struct AddressAddressUIntMapping { Mapping innerMapping; } struct AddressUIntUIntMapping { Mapping innerMapping; } struct AddressUIntUInt8Mapping { Mapping innerMapping; } struct AddressBytes32Bytes32Mapping { Mapping innerMapping; } struct AddressBytes4BoolMapping { Mapping innerMapping; } struct AddressBytes4Bytes32Mapping { Mapping innerMapping; } struct UIntAddressUIntMapping { Mapping innerMapping; } struct UIntAddressAddressMapping { Mapping innerMapping; } struct UIntAddressBoolMapping { Mapping innerMapping; } struct UIntUIntAddressMapping { Mapping innerMapping; } struct UIntUIntBytes32Mapping { Mapping innerMapping; } struct UIntUIntUIntMapping { Mapping innerMapping; } struct Bytes32UIntUIntMapping { Mapping innerMapping; } struct AddressUIntUIntUIntMapping { Mapping innerMapping; } struct AddressUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct UIntAddressAddressBoolMapping { Bool innerMapping; } struct UIntUIntUIntBytes32Mapping { Mapping innerMapping; } struct Bytes32UIntUIntUIntMapping { Mapping innerMapping; } bytes32 constant SET_IDENTIFIER = "set"; struct Set { UInt count; Mapping indexes; Mapping values; } struct AddressesSet { Set innerSet; } struct CounterSet { Set innerSet; } bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; struct OrderedSet { UInt count; Bytes32 first; Bytes32 last; Mapping nextValues; Mapping previousValues; } struct OrderedUIntSet { OrderedSet innerSet; } struct OrderedAddressesSet { OrderedSet innerSet; } struct Bytes32SetMapping { Set innerMapping; } struct AddressesSetMapping { Bytes32SetMapping innerMapping; } struct UIntSetMapping { Bytes32SetMapping innerMapping; } struct Bytes32OrderedSetMapping { OrderedSet innerMapping; } struct UIntOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } struct AddressOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert(); } } function init(Config storage self, Storage _store, bytes32 _crate) internal { self.store = _store; self.crate = _crate; } function init(UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(Config storage self, UInt storage item, uint _value) internal { self.store.setUInt(self.crate, item.id, _value); } function set(Config storage self, UInt storage item, bytes32 _salt, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, UInt8 storage item, uint8 _value) internal { self.store.setUInt8(self.crate, item.id, _value); } function set(Config storage self, UInt8 storage item, bytes32 _salt, uint8 _value) internal { self.store.setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Int storage item, int _value) internal { self.store.setInt(self.crate, item.id, _value); } function set(Config storage self, Int storage item, bytes32 _salt, int _value) internal { self.store.setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Address storage item, address _value) internal { self.store.setAddress(self.crate, item.id, _value); } function set(Config storage self, Address storage item, bytes32 _salt, address _value) internal { self.store.setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bool storage item, bool _value) internal { self.store.setBool(self.crate, item.id, _value); } function set(Config storage self, Bool storage item, bytes32 _salt, bool _value) internal { self.store.setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bytes32 storage item, bytes32 _value) internal { self.store.setBytes32(self.crate, item.id, _value); } function set(Config storage self, Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, String storage item, string _value) internal { self.store.setString(self.crate, item.id, _value); } function set(Config storage self, String storage item, bytes32 _salt, string _value) internal { self.store.setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Mapping storage item, uint _key, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { self.store.setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(Config storage self, AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(Config storage self, Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(Config storage self, AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(Config storage self, OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(Config storage self, Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(Config storage self, Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(Config storage self, AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(Config storage self, Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(Config storage self, AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(Config storage self, OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(Config storage self, Set storage source, Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(Config storage self, AddressesSet storage source, AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(Config storage self, CounterSet storage source, CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(Config storage self, UInt storage item) internal view returns (uint) { return self.store.getUInt(self.crate, item.id); } function get(Config storage self, UInt storage item, bytes32 salt) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, UInt8 storage item) internal view returns (uint8) { return self.store.getUInt8(self.crate, item.id); } function get(Config storage self, UInt8 storage item, bytes32 salt) internal view returns (uint8) { return self.store.getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Int storage item) internal view returns (int) { return self.store.getInt(self.crate, item.id); } function get(Config storage self, Int storage item, bytes32 salt) internal view returns (int) { return self.store.getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Address storage item) internal view returns (address) { return self.store.getAddress(self.crate, item.id); } function get(Config storage self, Address storage item, bytes32 salt) internal view returns (address) { return self.store.getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bool storage item) internal view returns (bool) { return self.store.getBool(self.crate, item.id); } function get(Config storage self, Bool storage item, bytes32 salt) internal view returns (bool) { return self.store.getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bytes32 storage item) internal view returns (bytes32) { return self.store.getBytes32(self.crate, item.id); } function get(Config storage self, Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, String storage item) internal view returns (string) { return self.store.getString(self.crate, item.id); } function get(Config storage self, String storage item, bytes32 salt) internal view returns (string) { return self.store.getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Mapping storage item, uint _key) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(Config storage self, AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return self.store.getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(Config storage self, Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(Config storage self, AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(Config storage self, AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(Config storage self, Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(Config storage self, Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(Config storage self, OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(Config storage self, Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(Config storage self, Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(Config storage self, AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(Config storage self, CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(Config storage self, Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(Config storage self, Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(Config storage self, AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(Config storage self, CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /** @title Structure to incapsulate and organize iteration through different kinds of collections */ struct Iterator { uint limit; uint valuesLeft; bytes32 currentValue; bytes32 anchorKey; } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(Config storage self, OrderedUIntSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedSet storage item) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(Config storage self, OrderedUIntSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, OrderedAddressesSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (Iterator) { return Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-storage-lib/contracts/StorageContractAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageContractAdapter { StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { StorageInterface.init(store, _store, _crate); } } // File: @laborx/solidity-storage-lib/contracts/StorageInterfaceContract.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageInterfaceContract is StorageContractAdapter, Storage { bytes32 constant SET_IDENTIFIER = "set"; bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert("STORAGE_INTERFACE_CONTRACT_SANITY_CHECK_FAILED"); } } function init(StorageInterface.Config storage self, bytes32 _crate) internal { self.crate = _crate; } function init(StorageInterface.UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(StorageInterface.UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(StorageInterface.AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(StorageInterface.OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, uint _value) internal { _setUInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 _salt, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, uint8 _value) internal { _setUInt8(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 _salt, uint8 _value) internal { _setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, int _value) internal { _setInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 _salt, int _value) internal { _setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, address _value) internal { _setAddress(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 _salt, address _value) internal { _setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bool _value) internal { _setBool(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _salt, bool _value) internal { _setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _value) internal { _setBytes32(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, string _value) internal { _setString(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 _salt, string _value) internal { _setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { _setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(StorageInterface.Config storage self, StorageInterface.Set storage source, StorageInterface.Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(StorageInterface.Config storage self, StorageInterface.AddressesSet storage source, StorageInterface.AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(StorageInterface.Config storage self, StorageInterface.CounterSet storage source, StorageInterface.CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(StorageInterface.Config storage self, StorageInterface.UInt storage item) internal view returns (uint) { return getUInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 salt) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item) internal view returns (uint8) { return getUInt8(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 salt) internal view returns (uint8) { return getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item) internal view returns (int) { return getInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 salt) internal view returns (int) { return getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item) internal view returns (address) { return getAddress(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 salt) internal view returns (address) { return getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item) internal view returns (bool) { return getBool(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 salt) internal view returns (bool) { return getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item) internal view returns (bytes32) { return getBytes32(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.String storage item) internal view returns (string) { return getString(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 salt) internal view returns (string) { return getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /* ITERABLE */ function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (StorageInterface.Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (StorageInterface.Iterator) { return StorageInterface.Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(StorageInterface.Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-shared-lib/contracts/BaseByzantiumRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; /// @title Routing contract that is able to provide a way for delegating invocations with dynamic destination address. contract BaseByzantiumRouter { function() external payable { address _implementation = implementation(); assembly { let calldataMemoryOffset := mload(0x40) mstore(0x40, add(calldataMemoryOffset, calldatasize)) calldatacopy(calldataMemoryOffset, 0x0, calldatasize) let r := delegatecall(sub(gas, 10000), _implementation, calldataMemoryOffset, calldatasize, 0, 0) let returndataMemoryOffset := mload(0x40) mstore(0x40, add(returndataMemoryOffset, returndatasize)) returndatacopy(returndataMemoryOffset, 0x0, returndatasize) switch r case 1 { return(returndataMemoryOffset, returndatasize) } default { revert(0, 0) } } } /// @notice Returns destination address for future calls /// @dev abstract definition. should be implemented in sibling contracts /// @return destination address function implementation() internal view returns (address); } // File: @laborx/solidity-storage-lib/contracts/StorageAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageAdapter { using StorageInterface for *; StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { store.init(_store, _crate); } } // File: contracts/ChronoBankPlatformBackendProvider.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformBackendProvider is Owned { ChronoBankPlatformInterface public platformBackend; constructor(ChronoBankPlatformInterface _platformBackend) public { updatePlatformBackend(_platformBackend); } function updatePlatformBackend(ChronoBankPlatformInterface _updatedPlatformBackend) public onlyContractOwner returns (bool) { require(address(_updatedPlatformBackend) != 0x0, "PLATFORM_BACKEND_PROVIDER_INVALID_PLATFORM_ADDRESS"); platformBackend = _updatedPlatformBackend; return true; } } // File: contracts/ChronoBankPlatformRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformRouterCore { address internal platformBackendProvider; } contract ChronoBankPlatformCore { bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; /// @dev Asset's owner id StorageInterface.Bytes32UIntMapping internal assetOwnerIdStorage; /// @dev Asset's total supply StorageInterface.Bytes32UIntMapping internal assetTotalSupply; /// @dev Asset's name, for information purposes. StorageInterface.StringMapping internal assetName; /// @dev Asset's description, for information purposes. StorageInterface.StringMapping internal assetDescription; /// @dev Indicates if asset have dynamic or fixed supply StorageInterface.Bytes32BoolMapping internal assetIsReissuable; /// @dev Proposed number of decimals StorageInterface.Bytes32UInt8Mapping internal assetBaseUnit; /// @dev Holders wallets partowners StorageInterface.Bytes32UIntBoolMapping internal assetPartowners; /// @dev Holders wallets balance StorageInterface.Bytes32UIntUIntMapping internal assetWalletBalance; /// @dev Holders wallets allowance StorageInterface.Bytes32UIntUIntUIntMapping internal assetWalletAllowance; /// @dev Block number from which asset can be used StorageInterface.Bytes32UIntMapping internal assetBlockNumber; /// @dev Iterable mapping pattern is used for holders. StorageInterface.UInt internal holdersCountStorage; /// @dev Current address of the holder. StorageInterface.UIntAddressMapping internal holdersAddressStorage; /// @dev Addresses that are trusted with recovery proocedure. StorageInterface.UIntAddressBoolMapping internal holdersTrustStorage; /// @dev This is an access address mapping. Many addresses may have access to a single holder. StorageInterface.AddressUIntMapping internal holderIndexStorage; /// @dev List of symbols that exist in a platform StorageInterface.Set internal symbolsStorage; /// @dev Asset symbol to asset proxy mapping. StorageInterface.Bytes32AddressMapping internal proxiesStorage; /// @dev Co-owners of a platform. Has less access rights than a root contract owner StorageInterface.AddressBoolMapping internal partownersStorage; } contract ChronoBankPlatformRouter is BaseByzantiumRouter, ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageAdapter { /// @dev memory layout from Owned contract address public contractOwner; bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; constructor(address _platformBackendProvider) StorageAdapter(Storage(address(this)), CHRONOBANK_PLATFORM_CRATE) public { require(_platformBackendProvider != 0x0, "PLATFORM_ROUTER_INVALID_BACKEND_ADDRESS"); contractOwner = msg.sender; platformBackendProvider = _platformBackendProvider; } function implementation() internal view returns (address) { return ChronoBankPlatformBackendProvider(platformBackendProvider).platformBackend(); } } // File: contracts/lib/SafeMath.sol /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "SAFE_MATH_INVALID_MUL"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SAFE_MATH_INVALID_SUB"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SAFE_MATH_INVALID_ADD"); return c; } } // File: contracts/ChronoBankPlatform.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ProxyEventsEmitter { function emitTransfer(address _from, address _to, uint _value) public; function emitApprove(address _from, address _spender, uint _value) public; } /// @title ChronoBank Platform. /// /// The official ChronoBank assets platform powering TIME and LHT tokens, and possibly /// other unknown tokens needed later. /// Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed /// at some point, all the events keep appearing at the same place. /// /// Every asset is meant to be used through a proxy contract. Only one proxy contract have access /// rights for a particular asset. /// /// Features: transfers, allowances, supply adjustments, lost wallet access recovery. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankPlatform is ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageInterfaceContract, ChronoBankPlatformCore { uint constant OK = 1; using SafeMath for uint; uint constant CHRONOBANK_PLATFORM_SCOPE = 15000; uint constant CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS = CHRONOBANK_PLATFORM_SCOPE + 0; uint constant CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF = CHRONOBANK_PLATFORM_SCOPE + 1; uint constant CHRONOBANK_PLATFORM_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 2; uint constant CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE = CHRONOBANK_PLATFORM_SCOPE + 3; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE = CHRONOBANK_PLATFORM_SCOPE + 4; uint constant CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 5; uint constant CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 6; uint constant CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = CHRONOBANK_PLATFORM_SCOPE + 7; uint constant CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW = CHRONOBANK_PLATFORM_SCOPE + 8; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS = CHRONOBANK_PLATFORM_SCOPE + 9; uint constant CHRONOBANK_PLATFORM_INVALID_NEW_OWNER = CHRONOBANK_PLATFORM_SCOPE + 10; uint constant CHRONOBANK_PLATFORM_ALREADY_TRUSTED = CHRONOBANK_PLATFORM_SCOPE + 11; uint constant CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = CHRONOBANK_PLATFORM_SCOPE + 12; uint constant CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 13; uint constant CHRONOBANK_PLATFORM_INVALID_INVOCATION = CHRONOBANK_PLATFORM_SCOPE + 17; string public version = "0.2.0"; struct TransactionContext { address from; address to; address sender; uint fromHolderId; uint toHolderId; uint senderHolderId; uint balanceFrom; uint balanceTo; uint allowanceValue; } /// @dev Emits Error if called not by asset owner. modifier onlyOwner(bytes32 _symbol) { if (isOwner(msg.sender, _symbol)) { _; } } modifier onlyDesignatedManager(bytes32 _symbol) { if (isDesignatedAssetManager(msg.sender, _symbol)) { _; } } /// @dev UNAUTHORIZED if called not by one of partowners or contract's owner modifier onlyOneOfContractOwners() { if (contractOwner == msg.sender || partowners(msg.sender)) { _; } } /// @dev Emits Error if called not by asset proxy. modifier onlyProxy(bytes32 _symbol) { if (proxies(_symbol) == msg.sender) { _; } } /// @dev Emits Error if _from doesn't trust _to. modifier checkTrust(address _from, address _to) { if (isTrusted(_from, _to)) { _; } } /// @dev Emits Error if asset block number > current block number. modifier onlyAfterBlock(bytes32 _symbol) { if (block.number >= blockNumber(_symbol)) { _; } } constructor() StorageContractAdapter(this, CHRONOBANK_PLATFORM_CRATE) public { } function initStorage() public { init(partownersStorage, "partowners"); init(proxiesStorage, "proxies"); init(symbolsStorage, "symbols"); init(holdersCountStorage, "holdersCount"); init(holderIndexStorage, "holderIndex"); init(holdersAddressStorage, "holdersAddress"); init(holdersTrustStorage, "holdersTrust"); init(assetOwnerIdStorage, "assetOwner"); init(assetTotalSupply, "assetTotalSupply"); init(assetName, "assetName"); init(assetDescription, "assetDescription"); init(assetIsReissuable, "assetIsReissuable"); init(assetBlockNumber, "assetBlockNumber"); init(assetBaseUnit, "assetBaseUnit"); init(assetPartowners, "assetPartowners"); init(assetWalletBalance, "assetWalletBalance"); init(assetWalletAllowance, "assetWalletAllowance"); } /// @dev Asset symbol to asset details. /// @return { /// "_description": "will be null, since cannot store and return dynamic-sized types in storage (fixed in v0.4.24), /// } function assets(bytes32 _symbol) public view returns ( uint _owner, uint _totalSupply, string _name, string _description, bool _isReissuable, uint8 _baseUnit, uint _blockNumber ) { _owner = _assetOwner(_symbol); _totalSupply = totalSupply(_symbol); _name = name(_symbol); _description = description(_symbol); _isReissuable = isReissuable(_symbol); _baseUnit = baseUnit(_symbol); _blockNumber = blockNumber(_symbol); } function holdersCount() public view returns (uint) { return get(store, holdersCountStorage); } function holders(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } function symbols(uint _idx) public view returns (bytes32) { return get(store, symbolsStorage, _idx); } /// @notice Provides a cheap way to get number of symbols registered in a platform /// @return number of symbols function symbolsCount() public view returns (uint) { return count(store, symbolsStorage); } function proxies(bytes32 _symbol) public view returns (address) { return get(store, proxiesStorage, _symbol); } function partowners(address _address) public view returns (bool) { return get(store, partownersStorage, _address); } /// @notice Adds a co-owner of a contract. Might be more than one co-owner /// @dev Allowed to only contract onwer /// @param _partowner a co-owner of a contract /// @return result code of an operation function addPartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, true); return OK; } /// @notice Removes a co-owner of a contract /// @dev Should be performed only by root contract owner /// @param _partowner a co-owner of a contract /// @return result code of an operation function removePartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, false); return OK; } /// @notice Sets EventsHistory contract address. /// @dev Can be set only by owner. /// @param _eventsHistory MultiEventsHistory contract address. /// @return success. function setupEventsHistory(address _eventsHistory) public onlyContractOwner returns (uint errorCode) { _setEventsHistory(_eventsHistory); return OK; } /// @notice Check asset existance. /// @param _symbol asset symbol. /// @return asset existance. function isCreated(bytes32 _symbol) public view returns (bool) { return _assetOwner(_symbol) != 0; } /// @notice Returns asset decimals. /// @param _symbol asset symbol. /// @return asset decimals. function baseUnit(bytes32 _symbol) public view returns (uint8) { return get(store, assetBaseUnit, _symbol); } /// @notice Returns asset name. /// @param _symbol asset symbol. /// @return asset name. function name(bytes32 _symbol) public view returns (string) { return get(store, assetName, _symbol); } /// @notice Returns asset description. /// @param _symbol asset symbol. /// @return asset description. function description(bytes32 _symbol) public view returns (string) { return get(store, assetDescription, _symbol); } /// @notice Returns asset reissuability. /// @param _symbol asset symbol. /// @return asset reissuability. function isReissuable(bytes32 _symbol) public view returns (bool) { return get(store, assetIsReissuable, _symbol); } /// @notice Returns block number from which asset can be used. /// @param _symbol asset symbol. /// @return block number. function blockNumber(bytes32 _symbol) public view returns (uint) { return get(store, assetBlockNumber, _symbol); } /// @notice Returns asset owner address. /// @param _symbol asset symbol. /// @return asset owner address. function owner(bytes32 _symbol) public view returns (address) { return _address(_assetOwner(_symbol)); } /// @notice Check if specified address has asset owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function isOwner(address _owner, bytes32 _symbol) public view returns (bool) { return isCreated(_symbol) && (_assetOwner(_symbol) == getHolderId(_owner)); } /// @notice Checks if a specified address has asset owner or co-owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool) { uint holderId = getHolderId(_owner); return isCreated(_symbol) && (_assetOwner(_symbol) == holderId || get(store, assetPartowners, _symbol, holderId)); } /// @notice Checks if a provided address `_manager` has designated access to asset `_symbol`. /// @param _manager address that will become the asset manager /// @param _symbol asset symbol /// @return true if address is one of designated asset managers, false otherwise function isDesignatedAssetManager(address _manager, bytes32 _symbol) public view returns (bool) { uint managerId = getHolderId(_manager); return isCreated(_symbol) && get(store, assetPartowners, _symbol, managerId); } /// @notice Returns asset total supply. /// @param _symbol asset symbol. /// @return asset total supply. function totalSupply(bytes32 _symbol) public view returns (uint) { return get(store, assetTotalSupply, _symbol); } /// @notice Returns asset balance for a particular holder. /// @param _holder holder address. /// @param _symbol asset symbol. /// @return holder balance. function balanceOf(address _holder, bytes32 _symbol) public view returns (uint) { return _balanceOf(getHolderId(_holder), _symbol); } /// @notice Returns asset balance for a particular holder id. /// @param _holderId holder id. /// @param _symbol asset symbol. /// @return holder balance. function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return get(store, assetWalletBalance, _symbol, _holderId); } /// @notice Returns current address for a particular holder id. /// @param _holderId holder id. /// @return holder address. function _address(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } /// @notice Adds a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function addDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = _createHolderId(_manager); set(store, assetPartowners, _symbol, holderId, true); _emitter().emitOwnershipChange(0x0, _manager, _symbol); return OK; } /// @notice Removes a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function removeDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = getHolderId(_manager); set(store, assetPartowners, _symbol, holderId, false); _emitter().emitOwnershipChange(_manager, 0x0, _symbol); return OK; } /// @notice Sets Proxy contract address for a particular asset. /// @dev Can be set only once for each asset and only by contract owner. /// @param _proxyAddress Proxy contract address. /// @param _symbol asset symbol. /// @return success. function setProxy(address _proxyAddress, bytes32 _symbol) public onlyOneOfContractOwners returns (uint) { if (proxies(_symbol) != 0x0) { return CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS; } set(store, proxiesStorage, _symbol, _proxyAddress); return OK; } /// @notice Performes asset transfer for multiple destinations /// @param addresses list of addresses to receive some amount /// @param values list of asset amounts for according addresses /// @param _symbol asset symbol /// @return { /// "errorCode": "resultCode of an operation", /// "count": "an amount of succeeded transfers" /// } function massTransfer(address[] addresses, uint[] values, bytes32 _symbol) external onlyAfterBlock(_symbol) returns (uint errorCode, uint count) { require(addresses.length == values.length, "Different length of addresses and values for mass transfer"); require(_symbol != 0x0, "Asset's symbol cannot be 0"); return _massTransferDirect(addresses, values, _symbol); } function _massTransferDirect(address[] addresses, uint[] values, bytes32 _symbol) private returns (uint errorCode, uint count) { uint success = 0; TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = _createHolderId(txContext.from); for (uint idx = 0; idx < addresses.length && gasleft() > 110000; idx++) { uint value = values[idx]; if (value == 0) { _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); continue; } txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < value) { _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); continue; } if (txContext.from == addresses[idx]) { _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); continue; } txContext.toHolderId = _createHolderId(addresses[idx]); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); _transferDirect(value, _symbol, txContext); _emitter().emitTransfer(txContext.from, addresses[idx], _symbol, value, ""); success++; } return (OK, success); } /// @dev Transfers asset balance between holders wallets. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _transferDirect( uint _value, bytes32 _symbol, TransactionContext memory _txContext ) internal { set(store, assetWalletBalance, _symbol, _txContext.fromHolderId, _txContext.balanceFrom.sub(_value)); set(store, assetWalletBalance, _symbol, _txContext.toHolderId, _txContext.balanceTo.add(_value)); } /// @dev Transfers asset balance between holders wallets. /// Performs sanity checks and takes care of allowances adjustment. /// /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// /// @return success. function _transfer( uint _value, bytes32 _symbol, string _reference, TransactionContext memory txContext ) internal returns (uint) { // Should not allow to send to oneself. if (txContext.fromHolderId == txContext.toHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough balance. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); } // Should have enough allowance. txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (txContext.fromHolderId != txContext.senderHolderId && txContext.allowanceValue < _value ) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE); } _transferDirect(_value, _symbol, txContext); // Adjust allowance. _decrementWalletAllowance(_value, _symbol, txContext); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitTransfer(txContext.from, txContext.to, _symbol, _value, _reference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _decrementWalletAllowance( uint _value, bytes32 _symbol, TransactionContext memory txContext ) private { if (txContext.fromHolderId != txContext.senderHolderId) { set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, txContext.allowanceValue.sub(_value)); } } /// @dev Transfers asset balance between holders wallets. /// Can only be called by asset proxy. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender transfer initiator address. /// /// @return success. function proxyTransferWithReference( address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _sender; txContext.senderHolderId = getHolderId(_sender); txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = txContext.senderHolderId; return _transfer(_value, _symbol, _reference, txContext); } /// @dev Ask asset Proxy contract to emit ERC20 compliant Transfer event. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _proxyTransferEvent(uint _value, bytes32 _symbol, TransactionContext memory txContext) internal { address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitTransfer(txContext.from, txContext.to, _value); } } /// @notice Returns holder id for the specified address. /// @param _holder holder address. /// @return holder id. function getHolderId(address _holder) public view returns (uint) { return get(store, holderIndexStorage, _holder); } /// @dev Returns holder id for the specified address, creates it if needed. /// @param _holder holder address. /// @return holder id. function _createHolderId(address _holder) internal returns (uint) { uint _holderId = getHolderId(_holder); if (_holderId == 0) { _holderId = holdersCount() + 1; set(store, holderIndexStorage, _holder, _holderId); set(store, holdersAddressStorage, _holderId, _holder); set(store, holdersCountStorage, _holderId); } return _holderId; } function _assetOwner(bytes32 _symbol) internal view returns (uint) { return get(store, assetOwnerIdStorage, _symbol); } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// /// @return success. function issueAsset( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber ) public returns (uint) { return issueAssetWithInitialReceiver(_symbol, _value, _name, _description, _baseUnit, _isReissuable, _blockNumber, msg.sender); } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// @param _account address where issued balance will be held /// /// @return success. function issueAssetWithInitialReceiver( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account ) public onlyOneOfContractOwners returns (uint) { // Should have positive value if supply is going to be fixed. if (_value == 0 && !_isReissuable) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE); } // Should not be issued yet. if (isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED); } uint holderId = _createHolderId(_account); uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender); add(store, symbolsStorage, _symbol); set(store, assetOwnerIdStorage, _symbol, creatorId); set(store, assetTotalSupply, _symbol, _value); set(store, assetName, _symbol, _name); set(store, assetDescription, _symbol, _description); set(store, assetIsReissuable, _symbol, _isReissuable); set(store, assetBaseUnit, _symbol, _baseUnit); set(store, assetWalletBalance, _symbol, holderId, _value); set(store, assetBlockNumber, _symbol, _blockNumber); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _address(holderId)); return OK; } /// @notice Issues additional asset tokens if the asset have dynamic supply. /// /// Tokens issued with this call go straight to asset owner. /// Can only be called by designated asset manager only. /// Inherits all modifiers from reissueAssetToRecepient' function. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// /// @return success. function reissueAsset(bytes32 _symbol, uint _value) public returns (uint) { return reissueAssetToRecepient(_symbol, _value, msg.sender); } /// @notice Issues additional asset tokens `_symbol` if the asset have dynamic supply /// and sends them to recepient address `_to`. /// /// Can only be called by designated asset manager only. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// @param _to recepient address; instead of caller issued amount will be sent to this address /// /// @return success. function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public onlyDesignatedManager(_symbol) onlyAfterBlock(_symbol) returns (uint) { return _reissueAsset(_symbol, _value, _to); } function _reissueAsset(bytes32 _symbol, uint _value, address _to) private returns (uint) { require(_to != 0x0, "CHRONOBANK_PLATFORM_INVALID_RECEPIENT_ADDRESS"); TransactionContext memory txContext; txContext.to = _to; // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have dynamic supply. if (!isReissuable(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET); } uint _totalSupply = totalSupply(_symbol); // Resulting total supply should not overflow. if (_totalSupply + _value < _totalSupply) { return _emitErrorCode(CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW); } txContext.toHolderId = _createHolderId(_to); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); set(store, assetWalletBalance, _symbol, txContext.toHolderId, txContext.balanceTo.add(_value)); set(store, assetTotalSupply, _symbol, _totalSupply.add(_value)); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _to); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAsset(bytes32 _symbol, uint _value) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevoke(_symbol, _value, txContext.from); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevokeExternal(_symbol, _value, txContext.from, _externalReference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _revokeAsset(bytes32 _symbol, uint _value, TransactionContext memory txContext) private returns (uint) { // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough tokens. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS); } txContext.balanceFrom = txContext.balanceFrom.sub(_value); set(store, assetWalletBalance, _symbol, txContext.fromHolderId, txContext.balanceFrom); set(store, assetTotalSupply, _symbol, totalSupply(_symbol).sub(_value)); return OK; } /// @notice Passes asset ownership to specified address. /// /// Only ownership is changed, balances are not touched. /// Can only be called by asset owner. /// /// @param _symbol asset symbol. /// @param _newOwner address to become a new owner. /// /// @return success. function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) { if (_newOwner == 0x0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_NEW_OWNER); } uint newOwnerId = _createHolderId(_newOwner); uint assetOwner = _assetOwner(_symbol); // Should pass ownership to another holder. if (assetOwner == newOwnerId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } address oldOwner = _address(assetOwner); set(store, assetOwnerIdStorage, _symbol, newOwnerId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitOwnershipChange(oldOwner, _newOwner, _symbol); return OK; } /// @notice Check if specified holder trusts an address with recovery procedure. /// @param _from truster. /// @param _to trustee. /// @return trust existance. function isTrusted(address _from, address _to) public view returns (bool) { return get(store, holdersTrustStorage, getHolderId(_from), _to); } /// @notice Trust an address to perform recovery procedure for the caller. /// @param _to trustee. /// @return success. function trust(address _to) public returns (uint) { uint fromId = _createHolderId(msg.sender); // Should trust to another address. if (fromId == getHolderId(_to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should trust to yet untrusted. if (isTrusted(msg.sender, _to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ALREADY_TRUSTED); } set(store, holdersTrustStorage, fromId, _to, true); return OK; } /// @notice Revoke trust to perform recovery procedure from an address. /// @param _to trustee. /// @return success. function distrust(address _to) public checkTrust(msg.sender, _to) returns (uint) { set(store, holdersTrustStorage, getHolderId(msg.sender), _to, false); return OK; } /// @notice Perform recovery procedure. /// /// This function logic is actually more of an addAccess(uint _holderId, address _to). /// It grants another address access to recovery subject wallets. /// Can only be called by trustee of recovery subject. /// /// @param _from holder address to recover from. /// @param _to address to grant access to. /// /// @return success. function recover(address _from, address _to) public checkTrust(_from, msg.sender) returns (uint errorCode) { // Should recover to previously unused address. if (getHolderId(_to) != 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS); } // We take current holder address because it might not equal _from. // It is possible to recover from any old holder address, but event should have the current one. uint _fromHolderId = getHolderId(_from); address _fromRef = _address(_fromHolderId); set(store, holdersAddressStorage, _fromHolderId, _to); set(store, holderIndexStorage, _to, _fromHolderId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitRecovery(_fromRef, _to, msg.sender); return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Note: to revoke allowance, one needs to set allowance to 0. /// /// @param _value amount to allow. /// @param _symbol asset symbol. /// /// @return success. function _approve( uint _value, bytes32 _symbol, TransactionContext memory txContext ) internal returns (uint) { // Asset should exist. if (!isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (txContext.fromHolderId == txContext.senderHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (!(txContext.allowanceValue == 0 || _value == 0)) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_INVOCATION); } set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, _value); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitApprove(txContext.from, txContext.sender, _symbol, _value); address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitApprove(txContext.from, txContext.sender, _value); } return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Can only be called by asset proxy. /// /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _symbol asset symbol. /// @param _sender approve initiator address. /// /// @return success. function proxyApprove( address _spender, uint _value, bytes32 _symbol, address _sender ) public onlyProxy(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _spender; txContext.senderHolderId = _createHolderId(_spender); txContext.from = _sender; txContext.fromHolderId = _createHolderId(_sender); return _approve(_value, _symbol, txContext); } /// @notice Performs allowance transfer of asset balance between holders wallets. /// /// @dev Can only be called by asset proxy. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender allowance transfer initiator address. /// /// @return success. function proxyTransferFromWithReference( address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _from; txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = getHolderId(_from); txContext.senderHolderId = _to == _sender ? txContext.toHolderId : getHolderId(_sender); return _transfer(_value, _symbol, _reference, txContext); } /// @dev Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint) { return _allowance(getHolderId(_from), getHolderId(_spender), _symbol); } /// @dev Returns asset allowance from one holder to another. /// @param _fromId holder id that allowed spending. /// @param _toId holder id that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function _allowance(uint _fromId, uint _toId, bytes32 _symbol) internal view returns (uint) { return get(store, assetWalletAllowance, _symbol, _fromId, _toId); } function _emitter() private view returns (ChronoBankPlatformEmitter) { return ChronoBankPlatformEmitter(getEventsHistory()); } } // File: contracts/EtherTokenExchange.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetProxyInterface is ChronoBankAssetProxy {} contract EtherTokenExchange { uint constant OK = 1; event LogEtherDeposited(address indexed sender, uint amount); event LogEtherWithdrawn(address indexed sender, uint amount); ERC20Interface private token; uint private reentrancyFallbackGuard = 1; constructor(address _token) public { token = ERC20Interface(_token); } function getToken() public view returns (address) { return token; } function deposit() external payable { _deposit(msg.sender, msg.value); } function withdraw(uint _amount) external { require(token.allowance(msg.sender, address(this)) >= _amount, "ETHER_TOKEN_EXCHANGE_NO_APPROVE_PROVIDED"); uint _guardState = reentrancyFallbackGuard; require(token.transferFrom(msg.sender, address(this), _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FROM_FAILED"); if (reentrancyFallbackGuard == _guardState) { _withdraw(msg.sender, _amount); } } function tokenFallback(address _from, uint _value, bytes) external { _incrementGuard(); if (msg.sender == address(token)) { _withdraw(_from, _value); return; } ChronoBankAssetProxyInterface _proxy = ChronoBankAssetProxyInterface(address(token)); address _versionFor = _proxy.getVersionFor(_from); if (!(msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender)) ) { revert("ETHER_TOKEN_EXCHANGE_INVALID_TOKEN"); } _withdraw(_from, _value); } function () external payable { revert("ETHER_TOKEN_EXCHANGE_USE_DEPOSIT_INSTEAD"); } /* PRIVATE */ function _deposit(address _to, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.reissueAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_ISSUE_FAILURE"); require(_token.transfer(_to, _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FAILURE"); emit LogEtherDeposited(_to, _amount); } function _withdraw(address _from, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.revokeAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_REVOKE_FAILURE"); _from.transfer(_amount); emit LogEtherWithdrawn(_from, _amount); } function _incrementGuard() public { reentrancyFallbackGuard += 1; } }
Supports ChronoBankPlatform ability to return error codes from methods Assigned platform, immutable. Assigned symbol, immutable. Assigned name, immutable. Assigned symbol (from ERC20 standard), immutable Sets platform address, assigns symbol and name. Can be set only once. _chronoBankPlatform platform contract address. _symbol assigned symbol. _name assigned name. return success.
function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) public returns (bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; }
1,048,885
./full_match/42220/0x788C4B43B6E8a28858f2862D0A8af203C71B89af/sources/Users/alex/Desktop/repos/CRAD-DeFi/v2.0/poolRegistry/contracts/AbsNFT.sol
We cannot just use balanceOf to create the new tokenId because tokens can be burned (destroyed), so we need a separate counter.
function mint(address to, string memory tokenUri) public virtual { _mint(to, _tokenIds.current()); _setTokenURI(_tokenIds.current(),tokenUri); _tokenIds.increment(); }
16,320,760
/** *Submitted for verification at Etherscan.io on 2022-04-12 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } pragma solidity ^0.8.7; // Some hints to help with the math: // // https://mathopenref.com/graphfunctions.html // https://www.wolframalpha.com/input/?i2d=true&i=Integrate%5BPower%5Be%2Ckt%5D%2C%7Bt%2Ca%2Cb%7D%5D // https://www.wolframalpha.com/input/?i2d=true&i=plot+Piecewise%5B%7B%7BPower%5Be%2C4%5C%2840%29t-1%5C%2841%29%5D%2Ct%3C%3D1%7D%2C%7B1%2C1%3Ct%3C2%7D%2C%7BPower%5Be%2C-t%2B2%5D%2Ct%3E%3D2%7D%7D%5D%5C%2844%29+0.01%2BIntegrate%5BPiecewise%5B%7B%7BPower%5Be%2C4%5C%2840%29t-1%5C%2841%29%5D%2Ct%3C%3D1%7D%2C%7B1%2C1%3Ct%3C2%7D%2C%7BPower%5Be%2C-t%2B2%5D%2Ct%3E%3D2%7D%7D%5D%2Ct%5D+from+t%3D0+to+8 // // Special thanks to ABDK! // https://abdk.consulting // https://github.com/abdk-consulting // /** * @dev declare and safegaurd token allocations among a number of slices. */ library EmissionCurves { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; struct Curve { int128 timeStart; // time of emission start as 64.64 seconds int128 durationGrowth; // seconds until max emissions reached as 64.64 int128 expGrowth; // e^(expGrowth * t) t=[-durationGrowthI, 0) as +64.64 int128 durationMax; // seconds duration of max emissions as 64.64 int128 durationDecay; // seconds duration of emission decay phase as 64.64 int128 expDecay; // e^(expDecay * t) t=(0, durationDecayI] as -64.64 int128 A; // area under entire envelope in world units } function newCurve( uint256 timeStart, uint32 durationGrowth, uint8 expGrowth, uint32 durationMax, uint32 durationDecay, uint8 expDecay ) internal pure returns (Curve memory) { return newCurve64x64( timeStart.fromUInt(), uint256(durationGrowth).fromUInt(), uint256(expGrowth).fromUInt().div(uint256(10).fromUInt()), uint256(durationMax).fromUInt(), uint256(durationDecay).fromUInt(), uint256(expDecay).fromUInt().div(uint256(10).fromUInt())); } function newCurve64x64( int128 timeStart, int128 durationGrowth, int128 expGrowth, int128 durationMax, int128 durationDecay, int128 expDecay ) internal pure returns (Curve memory) { // It is easiest to treat the time of max emission as t=0 and growth phase // occuring before t=0 to avoid dealing with the asymptotic coming from -∞. // // area under growth era = ∫(-1, 0) e^(expGrowth * t) dt // = (1 - e^-expGrowth / expGrowth // int128 I_growth = expGrowth == 0 ? int128(0) : uint256(1).fromUInt().sub(expGrowth.neg().exp()).div(expGrowth); // After the growth phase, max emissions occur for the given duration. // // area under max emission era = ∫(0, 1) 1 dt // = 1 // //int128 I_max = 1; // After the max emission phase, emissions decay exponentially. // // area under decay era = ∫(0, 1) e^-(expDecay * t) dt // = (1 - e^-expDecay) / expDecay // int128 I_decay = expDecay == 0 ? int128(0) : uint256(1).fromUInt().sub(expDecay.neg().exp()).div(expDecay); return Curve( timeStart, durationGrowth, expGrowth, durationMax, durationDecay, expDecay, I_growth.mul(durationGrowth).add(durationMax).add(I_decay.mul(durationDecay)) ); } function calcGrowth(Curve storage curve, uint256 timestamp) public view returns (int128) { // time elapsed since curve start int128 t = timestamp.fromUInt().sub(curve.timeStart); if (t < 0) { return 0; } if (curve.durationGrowth == 0 && curve.durationMax == 0 && curve.durationDecay == 0) { // Since there's no envelope defined, minting may occur whenever, // so return the unit max and defer to total allocation limit. return uint256(1).fromUInt(); } if (t < curve.durationGrowth) { // convert time from world to integral coordinates to keep the math simple and no overflow t = t.div(curve.durationGrowth); return _integrateGrowth(curve, t) .mul(curve.durationGrowth) // scale to world coordinates .div(curve.A); // normalize against sum of all phases } t = t.sub(curve.durationGrowth); if (t < curve.durationMax) { return _integrateGrowth(curve, uint256(1).fromUInt()) // growth phase .mul(curve.durationGrowth) // in world coordinates .add(t) // add max emission area .div(curve.A); // normalize against sum of all phases } t = t.sub(curve.durationMax); if (t < curve.durationDecay) { // convert time from world to integral coordinates to keep the math simple and no overflow t = t.div(curve.durationDecay); return _integrateGrowth(curve, uint256(1).fromUInt()) // growth phase .mul(curve.durationGrowth) // scale to world coordinates .add(curve.durationMax) // max phase (already in world coords) .add(_integrateDecay(curve, t) // decay phase .mul(curve.durationDecay)) // scale to world coordinates .div(curve.A); // normalize against sum of all phases } // 100% return uint256(1).fromUInt(); } function _integrateGrowth(Curve storage curve, int128 t) private view returns (int128) { // // = ∫(-durationGrowthI, t-durationGrowthI) e^(expGrowth * T) dT // = (e^((t - durationGrowthI) * expGrowth) - e^(-durationGrowthI * expGrowth)) / expGrowth // return t .sub(uint256(1).fromUInt()) .mul(curve.expGrowth) .exp() .sub(curve.expGrowth.neg().exp()) .div(curve.expGrowth); } function _integrateDecay(Curve storage curve, int128 t) private view returns (int128) { // // = ∫(0,t) e^(-expDecay * T) dT // = (1 - e^(-expDecay * t)) / expDecay // return uint256(1).fromUInt() .sub(curve.expDecay.mul(t).neg().exp()) .div(curve.expDecay); } } // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @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); } /** * @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; } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.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); } // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.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); } // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @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); } } } } // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } /** * @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; } } /** * @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]; } } } } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 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); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @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; } } // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) /** * @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); } } // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) /** * @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); } } // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @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); } } /** * @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)); } } // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.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); } } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) /** * @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); } /** * @dev Extension of ERC1155 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. * * Multiple ERC1155 token ids represent different voting classes each having a distinct voting power multiplier. * Token ID 0 should represent the most common share so that the vast majority of accounts do not need * to send transactions to change the default token. * * 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. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. */ contract ERC20_1155Votes is ERC1155Supply, EIP712, IERC20Metadata, IERC20Permit { using Counters for Counters.Counter; uint256 private _n; // number of token ids (share classes) uint256 private _aggregateSupply; // aggregate supply summed over all token ids string private _name; string private _symbol; // _defaultToken stores each account's default token used for ERC20 approvals/transfers. // // Since the mapping returns 0 by default it is recommended that the most common token class // be represented as tokenId == 0. If tokenId 0 represents common shares, for example, then // this mapping will be sparsely filled. Most accounts would never call setDefaultToken // to change the default since they would only ever hold the common class/share. // mapping(address => uint256) _defaultToken; // Default token ID for ERC20 approvals/tansfers. struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; mapping(address => Counters.Counter) internal _nonces; // for ERC20 transfers only, not used for ERC1155 transfers mapping(address => mapping(address => uint256)) private _allowances; /** * @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 an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Constructs a set of `n` tokens with varying voting weights determined by a power function. */ constructor(string memory name_, string memory symbol_, string memory uri_, uint256 n) ERC1155(uri_) EIP712(name_, "1") { _name = name_; _symbol = symbol_; _n = n; } function setDefaultToken(uint256 id) public { _defaultToken[msg.sender] = id; } function defaultToken() public view returns (uint256) { return _defaultToken[msg.sender]; } /** * @dev Returns the IERC20Metadata name of the token set. */ function name() external view override returns (string memory) { return _name; } /** * @dev Returns the IERC20Metadata base symbol of all tokens. */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev Returns the IERC20Metadata decimals places of the tokens. */ function decimals() external view override returns (uint8) { return 18; } /** * @dev Returns the aggregate total supply of all tokens regardless of token class. */ function totalSupply() public view override returns (uint256 supply) { for (uint id = 0; id < _n; ++id) { supply += totalSupply(id); } } /** * @dev Returns the aggregate number of tokens over all classes owned by `account`. */ function balanceOf(address account) public view override returns (uint256 balance) { for (uint id = 0; id < _n; ++id) { balance += balanceOf(account, id); } } /** * @dev Amount of `owner`'s default token approved for transfer by `spender`. */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Approve transfers of up to `amount` of default token. */ function approve(address spender, uint256 amount) external override returns (bool) { require(amount == 0 || _allowances[msg.sender][spender] == 0, "ERC20_1155Votes: potential double approval exploit"); _approve(msg.sender, spender, amount); return true; } /** * @dev Transfer `amount` of default token from sender to `to` account. */ function transfer(address to, uint256 amount) external override returns (bool) { _safeTransferFrom(msg.sender, to, _defaultToken[msg.sender], amount, ""); // secondary event for the ERC20 interface emit Transfer(msg.sender, to, amount); return true; } /** * @dev Transfer `amount` of common shares (token id == 0) from `from` account to `to` account. */ function transferFrom(address from, address to, uint256 amount) external override returns (bool) { require(_allowances[msg.sender][from] >= amount, "ERC20_1155Votes: transfer exceeds allowance"); _safeTransferFrom(from, to, _defaultToken[msg.sender], amount, ""); // secondary event for the ERC20 interface emit Transfer(from, to, amount); return true; } /** * @dev Get the voing power of an amount of tokens. */ function votingPower(uint256 /*id*/, uint256 amount) public view virtual returns (uint256) { return amount; } /** * @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 returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view 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 returns (uint256) { require(blockNumber < block.number, "ERC20_1155Votes: 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 returns (uint256) { require(blockNumber < block.number, "ERC20_1155Votes: 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 { _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 { require(block.timestamp <= expiry, "ERC20_1155Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20_1155Votes: invalid nonce"); _delegate(signer, delegatee); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20_1155Votes: approve from the zero address"); require(spender != address(0), "ERC20_1155Votes: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Maximum aggregate token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224 amount) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual override { super._mint(account, id, amount, data); _aggregateSupply += amount; require(_aggregateSupply <= _maxSupply(), "ERC20_1155Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, votingPower(id, amount)); emit Transfer(address(0), account, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 id, uint256 amount) internal virtual override { super._burn(account, id, amount); _aggregateSupply -= amount; _writeCheckpoint(_totalSupplyCheckpoints, _subtract, votingPower(id, amount)); emit Transfer(account, address(0), amount); } /** * @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 override { super._safeTransferFrom(from, to, id, amount, data); _moveVotingPower(delegates(from), delegates(to), votingPower(id, 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 = 0; for (uint32 id = 0; id < _n; ++id) { delegatorBalance += votingPower(id, balanceOf(delegator, id)); } _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; } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } // EIP-2612 IERC20Permit ------------------------------------------------- /** * @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 See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC20Permit).interfaceId || interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC20Metadata).interfaceId || super.supportsInterface(interfaceId); } } // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) /** * @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; } /** * @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()); } } } // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) /** * @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; } } /** * @dev declare and safegaurd token allocations. */ abstract contract AllocationControl is AccessControl { using EnumerableSet for EnumerableSet.Bytes32Set; // ALLOCATOR_ROLE is the admin for granting allocation roles. bytes32 public constant ALLOCATOR_ROLE = keccak256("ALLOCATOR_ROLE"); // Other roles are defined dynamically to enable per-slice minting privileges. // For tracking mints against declared allocations. // struct Slice { uint256 tokenId; uint256 units; uint256 minted; } EnumerableSet.Bytes32Set private _roles; mapping(bytes32 => Slice) private _allocations; mapping(uint256 => uint256) private _supplyCapPerTokenId; uint256 private _totalSupplyCap; function allocationSlice(bytes32 role) public view returns (Slice memory) { return _allocations[role]; } function allocationTotalSupplyCap() public view returns (uint256) { return _totalSupplyCap; } function allocationSupplyCapPerTokenId(uint256 tokenId) public view returns (uint256) { return _supplyCapPerTokenId[tokenId]; } // Declares or adjusts a single allocation. // // 0. clear counters // 1. alter existing, recount units // 2. add new, count new units // 3. remove zeroed-out allocations only if not yet minted // function _allocationAllocate(bytes32 role, uint256 tokenId, uint256 units) internal { if (_roles.contains(role)) { // existing if (_allocations[role].minted > 0) { require(units >= _allocations[role].minted, "reallocation must include already minted slice"); require(tokenId == _allocations[role].tokenId, "cannot change allocation's tokenId if already minted"); } _totalSupplyCap -= _allocations[role].units; _supplyCapPerTokenId[tokenId] -= _allocations[role].units; _totalSupplyCap += units; _supplyCapPerTokenId[tokenId] += units; _allocations[role].units = units; } else { // new _roles.add(role); _setRoleAdmin(role, ALLOCATOR_ROLE); _totalSupplyCap += units; _supplyCapPerTokenId[tokenId] += units; _allocations[role] = Slice(tokenId, units, 0); } } function _onAllocationMint(bytes32 role, uint256 amount) internal { require(_allocations[role].minted + amount <= _allocations[role].units, "mint exceeds allocation"); _allocations[role].minted += amount; } } interface IAllocationMinter { function allocationSupplyAt(bytes32 role, uint256 timestamp) external view returns (uint256); function allocationAvailable(bytes32 role) external view returns (uint256); function allocationMint(address to, bytes32 role, uint256 amount) external; function allocationMinted(bytes32 role) external view returns (uint256); } /** * LG DAO - Main Protocol Token * * One Ring to rule them all, * One Ring to find them, * One Ring to bring them all * and in the ledger bind them.” * * ― J.K.W. Blockchain * * Through their voting power, LG token balances govern property directors and their * continuous reinvestment of net cash flows from multi-industry development projects * and associated Loci Bell (LB) tokens. (LB tokens are single-property multi-tranche * fixed-growth ERC1155 debt contracts.) * * LG's multi-class voting mechanism presents an ERC20 voting interface compatible with * popular on-chain governance UX while also presenting an ERC1155 multi-class interface * thereby enabling differentiation of expert voting power and common protocol equity. * * 65% of voting power is held by 97% of LG (a.k.a. ERC1155 LG). 35% of voting power is * controlled by DAO Foundation directors with less than 3% of LG (a.k.a. ERC1155 LGY). * Aggregate balances of ERC1155 LG/Y present as ERC20 LG token balances. * * LG token has built-in emission curves and allocation distribution by director role. * Tokens are minted on demand in their respective category according to distinct * emission curves or director grant. Chainges to allocations and curves may only occur * via governance vote. */ contract LG is ERC20_1155Votes, AllocationControl, IAllocationMinter { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; using EmissionCurves for EmissionCurves.Curve; bytes32 public constant RESERVE_ALLOCATION = keccak256("RESERVE_ALLOCATION"); bytes32 public constant ANON_ALLOCATION = keccak256("ANON_ALLOCATION"); bytes32 public constant LEGACY_ALLOCATION = keccak256("LEGACY_ALLOCATION"); bytes32 public constant RECM_ALLOCATION = keccak256("RECM_ALLOCATION"); bytes32 public constant WEB3_ALLOCATION = keccak256("WEB3_ALLOCATION"); bytes32 public constant DAO_ALLOCATION = keccak256("DAO_ALLOCATION"); bytes32 public constant Y_DAO_ALLOCATION = keccak256("Y_DAO_ALLOCATION"); bytes32 public constant LP_ALLOCATION = keccak256("LP_ALLOCATION"); bytes32 public constant TEAM_ALLOCATION = keccak256("TEAM_ALLOCATION"); mapping(bytes32 => EmissionCurves.Curve) curves; constructor(address daoMultisig, string memory baseURI) ERC20_1155Votes("Loci Global", "LG", baseURI, 2) { _grantRole(ALLOCATOR_ROLE, daoMultisig); _grantRole(ALLOCATOR_ROLE, msg.sender); _grantRole(WEB3_ALLOCATION, msg.sender); // LG DAO Long Term Reserves _allocationAllocate(RESERVE_ALLOCATION, 0, 185_000_000 * 1e18); // not minted // Anon Contributors _allocationAllocate( ANON_ALLOCATION, 0, 99_000_000 * 1e18); // Auction Emission // Legacy Contributors _allocationAllocate( LEGACY_ALLOCATION, 0, 51_500_000 * 1e18); // Gaurdians _allocationAllocate( RECM_ALLOCATION, 0, 24_400_000 * 1e18); _allocationAllocate( WEB3_ALLOCATION, 0, 15_100_000 * 1e18); // Core Technology _allocationAllocate( DAO_ALLOCATION, 0, 11_650_000 * 1e18); _allocationAllocate( Y_DAO_ALLOCATION, 1, 350_000 * 1e18); // 35% vote // Blockchain Launch _allocationAllocate( LP_ALLOCATION, 0, 20_700_000 * 1e18); // LP Reward Emission _allocationAllocate( TEAM_ALLOCATION, 0, 33_300_000 * 1e18); // Property, Operations, Agents // Theoretical caps if/when each allocation role mints 100% require(allocationTotalSupplyCap() == 441_000_000 * 1e18); // 185M non-mintable require(allocationSupplyCapPerTokenId(0) == 440_650_000 * 1e18); require(allocationSupplyCapPerTokenId(1) == 350_000 * 1e18); // Initial Emission Curves curves[ANON_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 26 * 7 * 86400, 30, // 6 months ramp-up e^3.0x 1 * 52 * 7 * 86400, // 1 year of max emissions 3 * 52 * 7 * 86400, 30); // 3 years of decay e^-3.0x curves[RECM_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 3 * 52 * 7 * 86400, 20, // 3 years of ramp-up e^2x 2 * 52 * 7 * 86400, // 2 years of max emissions 0, 0); curves[WEB3_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 3 * 52 * 7 * 86400, 20, // 3 years of ramp-up e^2x 2 * 52 * 7 * 86400, // 2 years of max emissions 0, 0); curves[DAO_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 3 * 52 * 7 * 86400, 20, // 3 years of ramp-up e^2x 2 * 52 * 7 * 86400, // 2 years of max emissions 0, 0); } function setURI(string memory newURI) public { _setURI(newURI); } function setCurve( bytes32 role, uint256 timeStart, uint32 durationGrowth, uint8 expGrowth, uint32 durationMax, uint32 durationDecay, uint8 expDecay ) public onlyRole(ALLOCATOR_ROLE) { curves[role] = EmissionCurves.newCurve(timeStart, durationGrowth, expGrowth, durationMax, durationDecay, expDecay); } function allocationAllocate(bytes32 role, uint256 id, uint256 units) public onlyRole(ALLOCATOR_ROLE) { require(id < 2, "invalid class"); _allocationAllocate(role, id, units); } function votingPower(uint256 id, uint256 amount) public view override returns (uint256) { require(id < 2, "invalid class"); return amount * (id == 1 ? 35 : 65) / allocationSupplyCapPerTokenId(id); } // IAllocationMinter ----------------------------------------------------- function allocationMint(address to, bytes32 role, uint256 amount) public override onlyRole(role) { Slice memory slice = allocationSlice(role); uint total = curves[role].calcGrowth(block.timestamp).mulu(slice.units * 1e5) / 1e5; uint256 available = total > slice.minted ? total - slice.minted : 0; require(amount <= available, "amount exceeds emissions available"); _onAllocationMint(role, amount); _mint(to, slice.tokenId, amount, ""); } function allocationSupplyAt(bytes32 role, uint256 timestamp) public view override returns (uint256) { return curves[role].calcGrowth(timestamp).mulu(allocationSlice(role).units * 1e5) / 1e5; } function allocationAvailable(bytes32 role) public view override returns (uint256) { Slice memory slice = allocationSlice(role); uint total = curves[role].calcGrowth(block.timestamp).mulu(slice.units * 1e5) / 1e5; return total > slice.minted ? total - slice.minted : 0; } function allocationMinted(bytes32 role) public view override returns (uint256) { return allocationSlice(role).minted; } // IERC165 --------------------------------------------------------------- /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC20_1155Votes, AccessControl) returns (bool) { return ERC20_1155Votes.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId); } }
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 returns (uint256) { require(blockNumber < block.number, "ERC20_1155Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); }
2,389,990
./partial_match/1/0x6A1d98DaE0963ab8898ba02b652D1647Bd758E47/sources/FRTPoolPHZT.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotesinPool(address account, uint blockNumber) public view returns (uint256) { require(blockNumber < block.number, "getPriorVotesinPool: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
15,464,996
/** * The Edgeless blackjack contract only allows calls from the authorized casino proxy contracts. * The proxy contract only forward moves if called by an authorized wallet owned by the Edgeless casino, but the game * data has to be signed by the player to show his approval. This way, Edgeless can provide a fluid game experience * without having to wait for transaction confirmations. * author: Julia Altenried **/ pragma solidity ^0.4.17; contract owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function owned() public{ owner = msg.sender; } function changeOwner(address newOwner) onlyOwner public { owner = newOwner; } } contract mortal is owned { function close() onlyOwner public{ selfdestruct(owner); } } contract casino is mortal{ /** the minimum bet**/ uint public minimumBet; /** the maximum bet **/ uint public maximumBet; /** tells if an address is authorized to call game functions **/ mapping(address => bool) public authorized; /** * constructur. initialize the contract with initial values. * @param minBet the minimum bet * maxBet the maximum bet **/ function casino(uint minBet, uint maxBet) public{ minimumBet = minBet; maximumBet = maxBet; } /** * allows the owner to change the minimum bet * @param newMin the new minimum bet **/ function setMinimumBet(uint newMin) onlyOwner public{ minimumBet = newMin; } /** * allows the owner to change the maximum bet * @param newMax the new maximum bet **/ function setMaximumBet(uint newMax) onlyOwner public{ maximumBet = newMax; } /** * authorize a address to call game functions. * @param addr the address to be authorized **/ function authorize(address addr) onlyOwner public{ authorized[addr] = true; } /** * deauthorize a address to call game functions. * @param addr the address to be deauthorized **/ function deauthorize(address addr) onlyOwner public{ authorized[addr] = false; } /** * checks if an address is authorized to call game functionality **/ modifier onlyAuthorized{ require(authorized[msg.sender]); _; } } contract blackjack is casino { /** the value of the cards: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K . Ace can be 1 or 11, of course. * the value of a card can be determined by looking up cardValues[cardId%13]**/ uint8[13] cardValues = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]; /** tells if the player already claimed his win **/ mapping(bytes32 => bool) public over; /** the bets of the games in case they have been initialized before stand **/ mapping(bytes32 => uint) bets; /** list of splits per game - length 0 in most cases **/ mapping(bytes32 => uint8[]) splits; /** tells if a hand of a given game has been doubled **/ mapping(bytes32 => mapping(uint8 => bool)) doubled; /** notify listeners that a new round of blackjack started **/ event NewGame(bytes32 indexed id, bytes32 deck, bytes32 cSeed, address player, uint bet); /** notify listeners of the game outcome **/ event Result(bytes32 indexed id, address player, uint value, bool isWin); /** notify listeners that the player doubled **/ event Double(bytes32 indexed id, uint8 hand); /** notify listeners that the player split **/ event Split(bytes32 indexed id, uint8 hand); /** * constructur. initialize the contract with a minimum bet. * @param minBet the minimum bet * maxBet the maximum bet **/ function blackjack(uint minBet, uint maxBet) casino(minBet, maxBet) public{ } /** * initializes a round of blackjack. * accepts the bet. * throws an exception if the bet is too low or a game with the given id has already been played or the bet was already paid. * @param player the address of the player * value the value of the bet in tokens * deck the hash of the deck * srvSeed the hash of the server seed * cSeed the plain client seed **/ function initGame(address player, uint value, bytes32 deck, bytes32 srvSeed, bytes32 cSeed) onlyAuthorized public{ //throw if game with id already exists. later maybe throw only if game with id is still running assert(value >= minimumBet && value <= maximumBet); assert(!over[srvSeed]&&bets[srvSeed]==0);//make sure the game hasn't been payed already bets[srvSeed] = value; assert(msg.sender.call(bytes4(keccak256("shift(address,uint256,bool)")),player, value, false)); NewGame(srvSeed, deck, cSeed, player, value); } /** * doubles the bet of the game with the given id if the correct amount is sent and the player did not double the hand yet. * @param player the player address * id the game id * hand the index of the hand being doubled * value the number of tokens sent by the player **/ function double(address player, bytes32 id, uint8 hand, uint value) onlyAuthorized public { require(!over[id]); require(checkBet(id, value));//make sure the game has been initialized and the transfered value is correct require(hand <= splits[id].length && !doubled[id][hand]);//make sure the hand has not been doubled yet doubled[id][hand] = true; bets[id] += value; assert(msg.sender.call(bytes4(keccak256("shift(address,uint256,bool)")),player, value, false)); Double(id, hand); } /** * splits the hands of the game with the given id if the correct amount is sent from the player address and the player * did not split yet. * @param player the player address * id the game id * hand the index of the hand being split * value the number of tokens sent by the player **/ function split(address player, bytes32 id, uint8 hand, uint value) onlyAuthorized public { require(!over[id]); require(checkBet(id, value));//make sure the game has been initialized and the transfered value is correct require(splits[id].length < 3); splits[id].push(hand); bets[id] += value; assert(msg.sender.call(bytes4(keccak256("shift(address,uint256,bool)")),player, value, false)); Split(id,hand); } /** * by surrendering half the bet is returned to the player. * send the plain server seed to check if it's correct * @param player the player address * seed the server seed * bet the original bet **/ function surrender(address player, bytes32 seed, uint bet) onlyAuthorized public { var id = keccak256(seed); require(!over[id]); over[id] = true; if(bets[id]>0){ assert(bets[id]==bet); assert(msg.sender.call(bytes4(keccak256("shift(address,uint256,bool)")),player,bet / 2, true)); Result(id, player, bet / 2, true); } else{ assert(msg.sender.call(bytes4(keccak256("shift(address,uint256,bool)")),player,bet / 2, false)); Result(id, player, bet / 2, false); } } /** * first checks if deck and the player's number of cards are correct, then checks if the player won and if so, sends the win. * @param player the player address * deck the partial deck * seed the plain server seed * numCards the number of cards per hand * splits the array of splits * doubled the array indicating if a hand was doubled * bet the original bet * deckHash the hash of the deck (for verification and logging) * cSeed the client seed (for logging) **/ function stand(address player, uint8[] deck, bytes32 seed, uint8[] numCards, uint8[] splits, bool[] doubled,uint bet, bytes32 deckHash, bytes32 cSeed) onlyAuthorized public { bytes32 gameId; gameId = keccak256(seed); assert(!over[gameId]); assert(splits.length == numCards.length - 1); over[gameId] = true; assert(checkDeck(deck, seed, deckHash));//plausibility check var (win,loss) = determineOutcome(deck, numCards, splits, doubled, bet); if(bets[gameId] > 0){//initGame method called before assert(checkBet(gameId, bet)); win += bets[gameId];//pay back the bet } else NewGame(gameId, deckHash, cSeed, player, bet); if (win > loss){ assert(msg.sender.call(bytes4(keccak256("shift(address,uint256,bool)")),player, win-loss, true)); Result(gameId, player, win-loss, true); } else if(loss > win){//shift balance from the player to the casino assert(msg.sender.call(bytes4(keccak256("shift(address,uint256,bool)")),player, loss-win, false)); Result(gameId, player, loss-win, false); } else Result(gameId, player, 0, false); } /** * check if deck and casino seed are correct. * @param deck the partial deck * seed the server seed * deckHash the hash of the deck * @return true if correct **/ function checkDeck(uint8[] deck, bytes32 seed, bytes32 deckHash) constant public returns(bool correct) { if (keccak256(convertToBytes(deck), seed) != deckHash) return false; return true; } /** * converts an uint8 array to bytes * @param byteArray the uint8 array to be converted * @return the bytes **/ function convertToBytes(uint8[] byteArray) internal constant returns(bytes b) { b = new bytes(byteArray.length); for (uint8 i = 0; i < byteArray.length; i++) b[i] = byte(byteArray[i]); } /** * checks if the correct amount was paid for the initial bet + splits and doubles. * @param gameId the game id * bet the bet * @return true if correct * */ function checkBet(bytes32 gameId, uint bet) internal constant returns (bool correct){ uint factor = splits[gameId].length + 1; for(uint8 i = 0; i < splits[gameId].length+1; i++){ if(doubled[gameId][i]) factor++; } return bets[gameId] == bet * factor; } /** * determines the outcome of a game and returns the win. * in case of a loss, win is 0. * @param cards the cards / partial deck * numCards the number of cards per hand * splits the array of splits * doubled the array indicating if a hand was doubled * bet the original bet * @return the total win of all hands **/ function determineOutcome(uint8[] cards, uint8[] numCards, uint8[] splits, bool[] doubled, uint bet) constant public returns(uint totalWin, uint totalLoss) { var playerValues = getPlayerValues(cards, numCards, splits); var (dealerValue, dealerBJ) = getDealerValue(cards, sum(numCards)); uint win; uint loss; for (uint8 h = 0; h < numCards.length; h++) { uint8 playerValue = playerValues[h]; //bust if value > 21 if (playerValue > 21){ win = 0; loss = bet; } //player blackjack but no dealer blackjack else if (numCards.length == 1 && playerValue == 21 && numCards[h] == 2 && !dealerBJ) { win = bet * 3 / 2; //pay 3 to 2 loss = 0; } //player wins regularly else if (playerValue > dealerValue || dealerValue > 21){ win = bet; loss = 0; } //tie else if (playerValue == dealerValue){ win = 0; loss = 0; } //player looses else{ win = 0; loss = bet; } if (doubled[h]){ win *= 2; loss *= 2; } totalWin += win; totalLoss += loss; } } /** * calculates the value of the player's hands. * @param cards holds the (partial) deck. * numCards the number of cards per player hand * pSplits the player's splits (hand index) * @return the values of the player's hands **/ function getPlayerValues(uint8[] cards, uint8[] numCards, uint8[] pSplits) constant internal returns(uint8[5] playerValues) { uint8 cardIndex; uint8 splitIndex; (cardIndex, splitIndex, playerValues) = playHand(0, 0, 0, playerValues, cards, numCards, pSplits); } /** * recursively plays the player's hands. * @param hIndex the hand index * cIndex the index of the next card to draw * sIndex the index of the next split, if there is any * playerValues the values of the player's hands (not yet complete) * cards holds the (partial) deck. * numCards the number of cards per player hand * pSplits the array of splits * @return the values of the player's hands and the current card index **/ function playHand(uint8 hIndex, uint8 cIndex, uint8 sIndex, uint8[5] playerValues, uint8[] cards, uint8[] numCards, uint8[] pSplits) constant internal returns(uint8, uint8, uint8[5]) { playerValues[hIndex] = cardValues[cards[cIndex] % 13]; cIndex = cIndex < 4 ? cIndex + 2 : cIndex + 1; while (sIndex < pSplits.length && pSplits[sIndex] == hIndex) { sIndex++; (cIndex, sIndex, playerValues) = playHand(sIndex, cIndex, sIndex, playerValues, cards, numCards, pSplits); } uint8 numAces = playerValues[hIndex] == 11 ? 1 : 0; uint8 card; for (uint8 i = 1; i < numCards[hIndex]; i++) { card = cards[cIndex] % 13; playerValues[hIndex] += cardValues[card]; if (card == 0) numAces++; cIndex = cIndex < 4 ? cIndex + 2 : cIndex + 1; } while (numAces > 0 && playerValues[hIndex] > 21) { playerValues[hIndex] -= 10; numAces--; } return (cIndex, sIndex, playerValues); } /** * calculates the value of a dealer's hand. * @param cards holds the (partial) deck. * numCards the number of cards the player holds * @return the value of the dealer's hand and a flag indicating if the dealer has got a blackjack **/ function getDealerValue(uint8[] cards, uint8 numCards) constant internal returns(uint8 dealerValue, bool bj) { //dealer always receives second and forth card uint8 card = cards[1] % 13; uint8 card2 = cards[3] % 13; dealerValue = cardValues[card] + cardValues[card2]; uint8 numAces; if (card == 0) numAces++; if (card2 == 0) numAces++; if (dealerValue > 21) { //2 aces,count as 12 dealerValue -= 10; numAces--; } else if (dealerValue == 21) { return (21, true); } //take cards until value reaches 17 or more. uint8 i; while (dealerValue < 17) { card = cards[numCards + i + 2] % 13; dealerValue += cardValues[card]; if (card == 0) numAces++; if (dealerValue > 21 && numAces > 0) { dealerValue -= 10; numAces--; } i++; } } /** * sums up the given numbers * note: no overflow possible as player will always hold less than 100 cards * @param numbers the numbers to sum up * @return the sum of the numbers **/ function sum(uint8[] numbers) constant internal returns(uint8 s) { for (uint i = 0; i < numbers.length; i++) { s += numbers[i]; } } }
recursively plays the player's hands. hIndex the hand index cIndex the index of the next card to draw sIndex the index of the next split, if there is any playerValues the values of the player's hands (not yet complete) cards holds the (partial) deck. numCards the number of cards per player hand pSplits the array of splits return the values of the player's hands and the current card index/
function playHand(uint8 hIndex, uint8 cIndex, uint8 sIndex, uint8[5] playerValues, uint8[] cards, uint8[] numCards, uint8[] pSplits) constant internal returns(uint8, uint8, uint8[5]) { playerValues[hIndex] = cardValues[cards[cIndex] % 13]; cIndex = cIndex < 4 ? cIndex + 2 : cIndex + 1; while (sIndex < pSplits.length && pSplits[sIndex] == hIndex) { sIndex++; (cIndex, sIndex, playerValues) = playHand(sIndex, cIndex, sIndex, playerValues, cards, numCards, pSplits); } uint8 numAces = playerValues[hIndex] == 11 ? 1 : 0; uint8 card; for (uint8 i = 1; i < numCards[hIndex]; i++) { card = cards[cIndex] % 13; playerValues[hIndex] += cardValues[card]; if (card == 0) numAces++; cIndex = cIndex < 4 ? cIndex + 2 : cIndex + 1; } while (numAces > 0 && playerValues[hIndex] > 21) { playerValues[hIndex] -= 10; numAces--; } return (cIndex, sIndex, playerValues); }
14,067,025
// SPDX-License-Identifier: MIT 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) } } } 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); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @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); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @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 tokenId); /** * @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); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @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); } // File: ERC2000000.sol pragma solidity ^0.8.7; library Address { function isContract(address account) internal view returns (bool) { uint size; assembly { size := extcodesize(account) } return size > 0; } } abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; // Mapping from token ID to owner address address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; 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 (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count; uint length= _owners.length; for( uint i; i < length; ++i ){ if( owner == _owners[i] ) ++count; } delete length; return count; } /** * @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 {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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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 tokenId < _owners.length && _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); _owners.push(to); emit Transfer(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); _owners[tokenId] = address(0); emit Transfer(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 of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(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 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 {} } pragma solidity ^0.8.7; /** * @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 but rips out the core of the gas-wasting processing that comes from OpenZeppelin. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { /** * @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-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < _owners.length, "ERC721Enumerable: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint count; for(uint i; i < _owners.length; i++){ if(owner == _owners[i]){ if(count == index) return i; else count++; } } revert("ERC721Enumerable: owner index out of bounds"); } } pragma solidity ^0.8.7; contract MetamonGoLand is ERC721Enumerable, Ownable { using Strings for uint256; string private uriPrefix = ""; string private uriSuffix = ".json"; string public hiddenURL = "ipfs://QmR8kGw6oZUQ71yWTPY6ZPYAbVJqdq7s9sui5RqNKxAyLW"; uint256 public cost = 0.45 ether; uint16 public maxNFTPerWallet = 250; uint16 public constant maxSupply = 10000; uint8 public maxMintAmountPerTx = 50; bool public paused = true; bool public wlpaused = true; bool public reveal = false; bytes32 public whitelistMerkleRoot ; constructor() ERC721("Metamon Go Land ", "Mtmngl") { } function publicSale(uint16 _mintAmount) external payable { uint16 totalSupply = uint16(_owners.length); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); require(_mintAmount <= maxMintAmountPerTx, "Exceeds max per transaction."); require(!paused, "The contract is paused!"); require(msg.value == cost * _mintAmount, "Insufficient funds!"); for(uint8 i; i < _mintAmount; i++) { _mint(msg.sender, totalSupply + i); } delete totalSupply; delete _mintAmount; } function setWhitelistMerkleRoot(bytes32 _whitelistMerkleRoot) external onlyOwner { whitelistMerkleRoot = _whitelistMerkleRoot; } function getLeafNode(address _leaf) internal pure returns (bytes32 temp) { return keccak256(abi.encodePacked(_leaf)); } function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { return MerkleProof.verify(proof, whitelistMerkleRoot, leaf); } function preSale(uint16 _mintAmount , bytes32[] calldata merkleProof) external payable { bytes32 leafnode = getLeafNode(msg.sender); require(_verify(leafnode , merkleProof ), "Invalid merkle proof"); uint16 totalSupply = uint16(_owners.length); require(_mintAmount <= maxMintAmountPerTx, "Exceeds max per transaction."); require(!wlpaused, "The contract is paused!"); require(msg.value == cost * _mintAmount, "Insufficient funds!"); for(uint8 i; i < _mintAmount; i++) { _mint(msg.sender, totalSupply + i); } delete totalSupply; delete _mintAmount; } function Reserve(uint16 _mintAmount, address _receiver) external onlyOwner { uint16 totalSupply = uint16(_owners.length); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); for(uint16 i; i < _mintAmount; i++) { _mint(_receiver , totalSupply + i); } delete _mintAmount; delete _receiver; delete totalSupply; } function Airdrop(uint16 _mintAmount, address _receiver) external onlyOwner { uint16 totalSupply = uint16(_owners.length); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); for(uint16 i; i < _mintAmount; i++) { _mint(_receiver , totalSupply + i); } delete _mintAmount; delete _receiver; delete totalSupply; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (reveal == false) { return hiddenURL; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed() external onlyOwner { reveal = !reveal; } function setNFTPerWallet(uint8 _limit) external onlyOwner{ maxNFTPerWallet = _limit; delete _limit; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) external onlyOwner { hiddenURL = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) external onlyOwner { uriPrefix = _uriPrefix; } function setPublicSale() external onlyOwner { paused = !paused; wlpaused = true; } function setPresale() external onlyOwner { wlpaused = !wlpaused; } function setCost(uint _cost) external onlyOwner{ cost = _cost; } function setMaxMintAmountPerTx(uint8 _maxtx) external onlyOwner{ maxMintAmountPerTx = _maxtx; } function withdraw() external onlyOwner { uint _balance = address(this).balance; payable(msg.sender).transfer(_balance ); } function _mint(address to, uint256 tokenId) internal virtual override { _owners.push(to); emit Transfer(address(0), to, tokenId); } function _baseURI() internal view returns (string memory) { return uriPrefix; } }
See {IERC165-supportsInterface}./
function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.7; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
275,456
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract CaiShen is Ownable { struct Gift { bool exists; // 0 Only true if this exists uint giftId; // 1 The gift ID address giver; // 2 The address of the giver address recipient; // 3 The address of the recipient uint expiry; // 4 The expiry datetime of the timelock as a // Unix timestamp uint amount; // 5 The amount of ETH bool redeemed; // 6 Whether the funds have already been redeemed string giverName; // 7 The giver's name string message; // 8 A message from the giver to the recipient uint timestamp; // 9 The timestamp of when the gift was given } // Total fees gathered since the start of the contract or the last time // fees were collected, whichever is latest uint public feesGathered; // Each gift has a unique ID. If you increment this value, you will get // an unused gift ID. uint public nextGiftId; // Maps each recipient address to a list of giftIDs of Gifts they have // received. mapping (address => uint[]) public recipientToGiftIds; // Maps each gift ID to its associated gift. mapping (uint => Gift) public giftIdToGift; event Constructed (address indexed by, uint indexed amount); event CollectedAllFees (address indexed by, uint indexed amount); event DirectlyDeposited(address indexed from, uint indexed amount); event Gave (uint indexed giftId, address indexed giver, address indexed recipient, uint amount, uint expiry); event Redeemed (uint indexed giftId, address indexed giver, address indexed recipient, uint amount); // Constructor function CaiShen() public payable { Constructed(msg.sender, msg.value); } // Fallback function which allows this contract to receive funds. function () public payable { // Sending ETH directly to this contract does nothing except log an // event. DirectlyDeposited(msg.sender, msg.value); } //// Getter functions: function getGiftIdsByRecipient (address recipient) public view returns (uint[]) { return recipientToGiftIds[recipient]; } //// Contract functions: // Call this function while sending ETH to give a gift. // @recipient: the recipient's address // @expiry: the Unix timestamp of the expiry datetime. // @giverName: the name of the giver // @message: a personal message // Tested in test/test_give.js and test/TestGive.sol function give (address recipient, uint expiry, string giverName, string message) public payable returns (uint) { address giver = msg.sender; // Validate the giver address assert(giver != address(0)); // The gift must be a positive amount of ETH uint amount = msg.value; require(amount > 0); // The expiry datetime must be in the future. // The possible drift is only 12 minutes. // See: https://consensys.github.io/smart-contract-best-practices/recommendations/#timestamp-dependence require(expiry > now); // The giver and the recipient must be different addresses require(giver != recipient); // The recipient must be a valid address require(recipient != address(0)); // Make sure nextGiftId is 0 or positive, or this contract is buggy assert(nextGiftId >= 0); // Calculate the contract owner's fee uint feeTaken = fee(amount); assert(feeTaken >= 0); // Increment feesGathered feesGathered = SafeMath.add(feesGathered, feeTaken); // Shave off the fee from the amount uint amtGiven = SafeMath.sub(amount, feeTaken); assert(amtGiven > 0); // If a gift with this new gift ID already exists, this contract is buggy. assert(giftIdToGift[nextGiftId].exists == false); // Update the mappings recipientToGiftIds[recipient].push(nextGiftId); giftIdToGift[nextGiftId] = Gift(true, nextGiftId, giver, recipient, expiry, amtGiven, false, giverName, message, now); uint giftId = nextGiftId; // Increment nextGiftId nextGiftId = SafeMath.add(giftId, 1); // If a gift with this new gift ID already exists, this contract is buggy. assert(giftIdToGift[nextGiftId].exists == false); // Log the event Gave(giftId, giver, recipient, amount, expiry); return giftId; } // Call this function to redeem a gift of ETH. // Tested in test/test_redeem.js function redeem (uint giftId) public { // The giftID should be 0 or positive require(giftId >= 0); // The gift must exist and must not have already been redeemed require(isValidGift(giftIdToGift[giftId])); // The recipient must be the caller of this function address recipient = giftIdToGift[giftId].recipient; require(recipient == msg.sender); // The current datetime must be the same or after the expiry timestamp require(now >= giftIdToGift[giftId].expiry); //// If the following assert statements are triggered, this contract is //// buggy. // The amount must be positive because this is required in give() uint amount = giftIdToGift[giftId].amount; assert(amount > 0); // The giver must not be the recipient because this was asserted in give() address giver = giftIdToGift[giftId].giver; assert(giver != recipient); // Make sure the giver is valid because this was asserted in give(); assert(giver != address(0)); // Update the gift to mark it as redeemed, so that the funds cannot be // double-spent giftIdToGift[giftId].redeemed = true; // Transfer the funds recipient.transfer(amount); // Log the event Redeemed(giftId, giftIdToGift[giftId].giver, recipient, amount); } // Calculate the contract owner's fee // Tested in test/test_fee.js function fee (uint amount) public pure returns (uint) { if (amount <= 0.01 ether) { return 0; } else if (amount > 0.01 ether) { return SafeMath.div(amount, 100); } } // Transfer the fees collected thus far to the contract owner. // Only the contract owner may invoke this function. // Tested in test/test_collect_fees.js function collectAllFees () public onlyOwner { // Store the fee amount in a temporary variable uint amount = feesGathered; // Make sure that the amount is positive require(amount > 0); // Set the feesGathered state variable to 0 feesGathered = 0; // Make the transfer owner.transfer(amount); CollectedAllFees(owner, amount); } // Returns true only if the gift exists and has not already been // redeemed function isValidGift(Gift gift) private pure returns (bool) { return gift.exists == true && gift.redeemed == false; } }
Returns true only if the gift exists and has not already been redeemed
function isValidGift(Gift gift) private pure returns (bool) { return gift.exists == true && gift.redeemed == false; }
14,099,822
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ // File: contracts/IAwooClaiming.sol pragma solidity 0.8.12; interface IAwooClaiming{ function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate) external; } // File: contracts/AwooModels.sol pragma solidity 0.8.12; struct AccrualDetails{ address ContractAddress; uint256[] TokenIds; uint256[] Accruals; uint256 TotalAccrued; } struct ClaimDetails{ address ContractAddress; uint32[] TokenIds; } struct SupportedContractDetails{ address ContractAddress; uint256 BaseRate; bool Active; } // File: contracts/IAwooClaimingV2.sol pragma solidity 0.8.12; interface IAwooClaimingV2{ function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate) external; function claim(address holder, ClaimDetails[] calldata requestedClaims) external; } // File: contracts/AddressChecksumStringUtil.sol pragma solidity ^0.8.0; // Derived from https://ethereum.stackexchange.com/a/63953, no license specified // Modified to remove unnecessary functionality and prepend the checksummed string address with "0x" /** * @dev This contract provides a set of pure functions for computing the EIP-55 * checksum of an account in formats friendly to both off-chain and on-chain * callers, as well as for checking if a given string hex representation of an * address has a valid checksum. These helper functions could also be repurposed * as a library that extends the `address` type. */ contract AddressChecksumStringUtil { function toChecksumString(address account) internal pure returns (string memory asciiString) { // convert the account argument from address to bytes. bytes20 data = bytes20(account); // create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // declare variable types. uint8 b; uint8 leftNibble; uint8 rightNibble; bool leftCaps; bool rightCaps; uint8 asciiOffset; // get the capitalized characters in the actual checksum. bool[40] memory caps = _toChecksumCapsFlags(account); // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. b = uint8(uint160(data) / (2**(8*(19 - i)))); leftNibble = b / 16; rightNibble = b - 16 * leftNibble; // locate and extract each capitalization status. leftCaps = caps[2*i]; rightCaps = caps[2*i + 1]; // get the offset from nibble value to ascii character for left nibble. asciiOffset = _getAsciiOffset(leftNibble, leftCaps); // add the converted character to the byte array. asciiBytes[2 * i] = bytes1(leftNibble + asciiOffset); // get the offset from nibble value to ascii character for right nibble. asciiOffset = _getAsciiOffset(rightNibble, rightCaps); // add the converted character to the byte array. asciiBytes[2 * i + 1] = bytes1(rightNibble + asciiOffset); } return string(abi.encodePacked("0x", string(asciiBytes))); } function _getAsciiOffset(uint8 nibble, bool caps) internal pure returns (uint8 offset) { // to convert to ascii characters, add 48 to 0-9, 55 to A-F, & 87 to a-f. if (nibble < 10) { offset = 48; } else if (caps) { offset = 55; } else { offset = 87; } } function _toChecksumCapsFlags(address account) internal pure returns (bool[40] memory characterCapitalized) { // convert the address to bytes. bytes20 a = bytes20(account); // hash the address (used to calculate checksum). bytes32 b = keccak256(abi.encodePacked(_toAsciiString(a))); // declare variable types. uint8 leftNibbleAddress; uint8 rightNibbleAddress; uint8 leftNibbleHash; uint8 rightNibbleHash; // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i; i < a.length; i++) { // locate the byte and extract each nibble for the address and the hash. rightNibbleAddress = uint8(a[i]) % 16; leftNibbleAddress = (uint8(a[i]) - rightNibbleAddress) / 16; rightNibbleHash = uint8(b[i]) % 16; leftNibbleHash = (uint8(b[i]) - rightNibbleHash) / 16; characterCapitalized[2 * i] = (leftNibbleAddress > 9 && leftNibbleHash > 7); characterCapitalized[2 * i + 1] = (rightNibbleAddress > 9 && rightNibbleHash > 7); } } // based on https://ethereum.stackexchange.com/a/56499/48410 function _toAsciiString(bytes20 data) internal pure returns (string memory asciiString) { // create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // declare variable types. uint8 b; uint8 leftNibble; uint8 rightNibble; // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. b = uint8(uint160(data) / (2 ** (8 * (19 - i)))); leftNibble = b / 16; rightNibble = b - 16 * leftNibble; // to convert to ascii characters, add 48 to 0-9 and 87 to a-f. asciiBytes[2 * i] = bytes1(leftNibble + (leftNibble < 10 ? 48 : 87)); asciiBytes[2 * i + 1] = bytes1(rightNibble + (rightNibble < 10 ? 48 : 87)); } return string(asciiBytes); } } // File: @openzeppelin/[email protected]/utils/Strings.sol // 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); } } // File: @openzeppelin/[email protected]/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @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; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 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)); } } // File: @openzeppelin/[email protected]/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @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); } // File: contracts/IAwooToken.sol pragma solidity 0.8.12; interface IAwooToken is IERC20 { function increaseVirtualBalance(address account, uint256 amount) external; function mint(address account, uint256 amount) external; function balanceOfVirtual(address account) external view returns(uint256); function spendVirtualAwoo(bytes32 hash, bytes memory sig, string calldata nonce, address account, uint256 amount) external; } // File: @openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/[email protected]/security/ReentrancyGuard.sol // 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]. */ 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 // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/[email protected]/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/[email protected]/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @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); } } // File: contracts/OwnerAdminGuard.sol pragma solidity 0.8.12; contract OwnerAdminGuard is Ownable { address[2] private _admins; bool private _adminsSet; /// @notice Allows the owner to specify two addresses allowed to administer this contract /// @param admins A 2 item array of addresses function setAdmins(address[2] calldata admins) public { require(admins[0] != address(0) && admins[1] != address(0), "Invalid admin address"); _admins = admins; _adminsSet = true; } function _isOwnerOrAdmin(address addr) internal virtual view returns(bool){ return addr == owner() || ( _adminsSet && ( addr == _admins[0] || addr == _admins[1] ) ); } modifier onlyOwnerOrAdmin() { require(_isOwnerOrAdmin(msg.sender), "Not an owner or admin"); _; } } // File: contracts/AuthorizedCallerGuard.sol pragma solidity 0.8.12; contract AuthorizedCallerGuard is OwnerAdminGuard { /// @dev Keeps track of which contracts are explicitly allowed to interact with certain super contract functionality mapping(address => bool) public authorizedContracts; event AuthorizedContractAdded(address contractAddress, address addedBy); event AuthorizedContractRemoved(address contractAddress, address removedBy); /// @notice Allows the owner or an admin to authorize another contract to override token accruals on an individual token level /// @param contractAddress The authorized contract address function addAuthorizedContract(address contractAddress) public onlyOwnerOrAdmin { require(_isContract(contractAddress), "Invalid contractAddress"); authorizedContracts[contractAddress] = true; emit AuthorizedContractAdded(contractAddress, _msgSender()); } /// @notice Allows the owner or an admin to remove an authorized contract /// @param contractAddress The contract address which should have its authorization revoked function removeAuthorizedContract(address contractAddress) public onlyOwnerOrAdmin { authorizedContracts[contractAddress] = false; emit AuthorizedContractRemoved(contractAddress, _msgSender()); } /// @dev Derived from @openzeppelin/contracts/utils/Address.sol function _isContract(address account) internal virtual view returns (bool) { if(account == address(0)) return false; // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } function _isAuthorizedContract(address addr) internal virtual view returns(bool){ return authorizedContracts[addr]; } modifier onlyAuthorizedCaller() { require(_isOwnerOrAdmin(_msgSender()) || _isAuthorizedContract(_msgSender()), "Sender is not authorized"); _; } modifier onlyAuthorizedContract() { require(_isAuthorizedContract(_msgSender()), "Sender is not authorized"); _; } } // File: contracts/AwooClaiming.sol pragma solidity 0.8.12; pragma experimental ABIEncoderV2; interface ISupportedContract { function tokensOfOwner(address owner) external view returns (uint256[] memory); function balanceOf(address owner) external view returns (uint256); function ownerOf(uint256 tokenId) external view returns (address); function exists(uint256 tokenId) external view returns (bool); } contract AwooClaiming is IAwooClaiming, Ownable, ReentrancyGuard { uint256 public accrualStart = 1646006400; //2022-02-28 00:00 UTC uint256 public accrualEnd; bool public claimingActive; /// @dev A collection of supported contracts. These are typically ERC-721, with the addition of the tokensOfOwner function. /// @dev These contracts can be deactivated but cannot be re-activated. Reactivating can be done by adding the same /// contract through addSupportedContract SupportedContractDetails[] public supportedContracts; /// @dev Keeps track of the last time a claim was made for each tokenId within the supported contract collection mapping(address => mapping(uint256 => uint256)) public lastClaims; /// @dev Allows the base accrual rates to be overridden on a per-tokenId level to support things like upgrades mapping(address => mapping(uint256 => uint256)) public baseRateTokenOverrides; address[2] private _admins; bool private _adminsSet; IAwooToken private _awooContract; /// @dev Base accrual rates are set a per-day rate so we change them to per-minute to allow for more frequent claiming uint64 private _baseRateDivisor = 1440; /// @dev Faciliates the maintence and functionality related to supportedContracts uint8 private _activeSupportedContractCount; mapping(address => uint8) private _supportedContractIds; /// @dev Keeps track of which contracts are explicitly allowed to override the base accrual rates mapping(address => bool) private _authorizedContracts; event TokensClaimed(address indexed claimedBy, uint256 qty); event ClaimingStatusChanged(bool newStatus, address changedBy); event AuthorizedContractAdded(address contractAddress, address addedBy); event AuthorizedContractRemoved(address contractAddress, address removedBy); constructor(uint256 accrualStartTimestamp) { require(accrualStartTimestamp > 0, "Invalid accrualStartTimestamp"); accrualStart = accrualStartTimestamp; } /// @notice Determines the amount of accrued virtual AWOO for the specified address, based on the /// base accural rates for each supported contract and how long has elapsed (in minutes) since the /// last claim was made for a give supported contract tokenId /// @param owner The address of the owner/holder of tokens for a supported contract /// @return A collection of accrued virtual AWOO and the tokens it was accrued on for each supported contract, and the total AWOO accrued function getTotalAccruals(address owner) public view returns (AccrualDetails[] memory, uint256) { // Initialize the array length based on the number of _active_ supported contracts AccrualDetails[] memory totalAccruals = new AccrualDetails[](_activeSupportedContractCount); uint256 totalAccrued; uint8 contractCount; // Helps us keep track of the index to use when setting the values for totalAccruals for(uint8 i = 0; i < supportedContracts.length; i++) { SupportedContractDetails memory contractDetails = supportedContracts[i]; if(contractDetails.Active){ contractCount++; // Get an array of tokenIds held by the owner for the supported contract uint256[] memory tokenIds = ISupportedContract(contractDetails.ContractAddress).tokensOfOwner(owner); uint256[] memory accruals = new uint256[](tokenIds.length); uint256 totalAccruedByContract; for (uint16 x = 0; x < tokenIds.length; x++) { uint32 tokenId = uint32(tokenIds[x]); uint256 accrued = getContractTokenAccruals(contractDetails.ContractAddress, contractDetails.BaseRate, tokenId); totalAccruedByContract+=accrued; totalAccrued+=accrued; tokenIds[x] = tokenId; accruals[x] = accrued; } AccrualDetails memory accrual = AccrualDetails(contractDetails.ContractAddress, tokenIds, accruals, totalAccruedByContract); totalAccruals[contractCount-1] = accrual; } } return (totalAccruals, totalAccrued); } /// @notice Claims all virtual AWOO accrued by the message sender, assuming the sender holds any supported contracts tokenIds function claimAll() external nonReentrant { require(claimingActive, "Claiming is inactive"); require(isValidHolder(), "No supported tokens held"); (AccrualDetails[] memory accruals, uint256 totalAccrued) = getTotalAccruals(_msgSender()); require(totalAccrued > 0, "No tokens have been accrued"); for(uint8 i = 0; i < accruals.length; i++){ AccrualDetails memory accrual = accruals[i]; if(accrual.TotalAccrued > 0){ for(uint16 x = 0; x < accrual.TokenIds.length;x++){ // Update the time that this token was last claimed lastClaims[accrual.ContractAddress][accrual.TokenIds[x]] = block.timestamp; } } } // A holder's virtual AWOO balance is stored in the $AWOO ERC-20 contract _awooContract.increaseVirtualBalance(_msgSender(), totalAccrued); emit TokensClaimed(_msgSender(), totalAccrued); } /// @notice Claims the accrued virtual AWOO from the specified supported contract tokenIds /// @param requestedClaims A collection of supported contract addresses and the specific tokenIds to claim from function claim(ClaimDetails[] calldata requestedClaims) external nonReentrant { require(claimingActive, "Claiming is inactive"); require(isValidHolder(), "No supported tokens held"); uint256 totalClaimed; for(uint8 i = 0; i < requestedClaims.length; i++){ ClaimDetails calldata requestedClaim = requestedClaims[i]; uint8 contractId = _supportedContractIds[requestedClaim.ContractAddress]; if(contractId == 0) revert("Unsupported contract"); SupportedContractDetails memory contractDetails = supportedContracts[contractId-1]; if(!contractDetails.Active) revert("Inactive contract"); for(uint16 x = 0; x < requestedClaim.TokenIds.length; x++){ uint32 tokenId = requestedClaim.TokenIds[x]; address tokenOwner = ISupportedContract(address(contractDetails.ContractAddress)).ownerOf(tokenId); if(tokenOwner != _msgSender()) revert("Invalid owner claim attempt"); uint256 claimableAmount = getContractTokenAccruals(contractDetails.ContractAddress, contractDetails.BaseRate, tokenId); if(claimableAmount > 0){ totalClaimed+=claimableAmount; // Update the time that this token was last claimed lastClaims[contractDetails.ContractAddress][tokenId] = block.timestamp; } } } if(totalClaimed > 0){ _awooContract.increaseVirtualBalance(_msgSender(), totalClaimed); emit TokensClaimed(_msgSender(), totalClaimed); } } /// @dev Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId function getContractTokenAccruals(address contractAddress, uint256 contractBaseRate, uint32 tokenId) private view returns(uint256){ uint256 lastClaimTime = lastClaims[contractAddress][tokenId]; uint256 accruedUntil = accrualEnd == 0 || block.timestamp < accrualEnd ? block.timestamp : accrualEnd; uint256 baseRate = baseRateTokenOverrides[contractAddress][tokenId] > 0 ? baseRateTokenOverrides[contractAddress][tokenId] : contractBaseRate; if (lastClaimTime > 0){ return (baseRate*(accruedUntil-lastClaimTime))/60; } else { return (baseRate*(accruedUntil-accrualStart))/60; } } /// @notice Allows an authorized contract to increase the base accrual rate for particular NFTs /// when, for example, upgrades for that NFT were purchased /// @param contractAddress The address of the supported contract /// @param tokenId The id of the token from the supported contract whose base accrual rate will be updated /// @param newBaseRate The new accrual base rate function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate) external onlyAuthorizedContract isValidBaseRate(newBaseRate) { require(tokenId > 0, "Invalid tokenId"); uint8 contractId = _supportedContractIds[contractAddress]; require(contractId > 0, "Unsupported contract"); require(supportedContracts[contractId-1].Active, "Inactive contract"); baseRateTokenOverrides[contractAddress][tokenId] = (newBaseRate/_baseRateDivisor); } /// @notice Allows the owner or an admin to set a reference to the $AWOO ERC-20 contract /// @param awooToken An instance of IAwooToken function setAwooTokenContract(IAwooToken awooToken) external onlyOwnerOrAdmin { _awooContract = awooToken; } /// @notice Allows the owner or an admin to set the date and time at which virtual AWOO accruing will stop /// @notice This will only be used if absolutely necessary and any AWOO that accrued before the end date will still be claimable /// @param timestamp The Epoch time at which accrual should end function setAccrualEndTimestamp(uint256 timestamp) external onlyOwnerOrAdmin { accrualEnd = timestamp; } /// @notice Allows the owner or an admin to add a contract whose tokens are eligible to accrue virtual AWOO /// @param contractAddress The contract address of the collection (typically ERC-721, with the addition of the tokensOfOwner function) /// @param baseRate The base accrual rate in wei units function addSupportedContract(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) { require(isContract(contractAddress), "Invalid contractAddress"); require(_supportedContractIds[contractAddress] == 0, "Contract already supported"); supportedContracts.push(SupportedContractDetails(contractAddress, baseRate/_baseRateDivisor, true)); _supportedContractIds[contractAddress] = uint8(supportedContracts.length); _activeSupportedContractCount++; } /// @notice Allows the owner or an admin to deactivate a supported contract so it no longer accrues virtual AWOO /// @param contractAddress The contract address that should be deactivated function deactivateSupportedContract(address contractAddress) external onlyOwnerOrAdmin { require(_supportedContractIds[contractAddress] > 0, "Unsupported contract"); supportedContracts[_supportedContractIds[contractAddress]-1].Active = false; supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = 0; _supportedContractIds[contractAddress] = 0; _activeSupportedContractCount--; } /// @notice Allows the owner or an admin to authorize another contract to override token accruals on an individual token level /// @param contractAddress The authorized contract address function addAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin { require(isContract(contractAddress), "Invalid contractAddress"); _authorizedContracts[contractAddress] = true; emit AuthorizedContractAdded(contractAddress, _msgSender()); } /// @notice Allows the owner or an admin to remove an authorized contract /// @param contractAddress The contract address which should have its authorization revoked function removeAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin { _authorizedContracts[contractAddress] = false; emit AuthorizedContractRemoved(contractAddress, _msgSender()); } /// @notice Allows the owner or an admin to set the base accrual rate for a support contract /// @param contractAddress The address of the supported contract /// @param baseRate The new base accrual rate in wei units function setBaseRate(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) { require(_supportedContractIds[contractAddress] > 0, "Unsupported contract"); supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = baseRate/_baseRateDivisor; } /// @notice Allows the owner to specify two addresses allowed to administer this contract /// @param adminAddresses A 2 item array of addresses function setAdmins(address[2] calldata adminAddresses) external onlyOwner { require(adminAddresses[0] != address(0) && adminAddresses[1] != address(0), "Invalid admin address"); _admins = adminAddresses; _adminsSet = true; } /// @notice Allows the owner or an admin to activate/deactivate claiming ability /// @param active The value specifiying whether or not claiming should be allowed function setClaimingActive(bool active) external onlyOwnerOrAdmin { claimingActive = active; emit ClaimingStatusChanged(active, _msgSender()); } /// @dev Derived from @openzeppelin/contracts/utils/Address.sol function isContract(address account) private view returns (bool) { if(account == address(0)) return false; // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /// @notice Determines whether or not the caller holds tokens for any of the supported contracts function isValidHolder() private view returns(bool) { for(uint8 i = 0; i < supportedContracts.length; i++){ SupportedContractDetails memory contractDetails = supportedContracts[i]; if(contractDetails.Active){ if(ISupportedContract(contractDetails.ContractAddress).balanceOf(_msgSender()) > 0) { return true; // No need to continue checking other collections if the holder has any of the supported tokens } } } return false; } modifier onlyAuthorizedContract() { require(_authorizedContracts[_msgSender()], "Sender is not authorized"); _; } modifier onlyOwnerOrAdmin() { require( _msgSender() == owner() || ( _adminsSet && ( _msgSender() == _admins[0] || _msgSender() == _admins[1] ) ), "Not an owner or admin"); _; } /// @dev To minimize the amount of unit conversion we have to do for comparing $AWOO (ERC-20) to virtual AWOO, we store /// virtual AWOO with 18 implied decimal places, so this modifier prevents us from accidentally using the wrong unit /// for base rates. For example, if holders of FangGang NFTs accrue at a rate of 1000 AWOO per fang, pre day, then /// the base rate should be 1000000000000000000000 modifier isValidBaseRate(uint256 baseRate) { require(baseRate >= 1 ether, "Base rate must be in wei units"); _; } } // File: @openzeppelin/[email protected]/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @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 Contracts guidelines: functions revert * instead 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, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @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. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @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; } /** * @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 this function is * overridden; * * 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 virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } 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] + 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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * 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: * * - `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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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: * * - `account` 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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(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); 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This 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 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 {} } // File: contracts/AwooToken.sol pragma solidity 0.8.12; contract AwooToken is IAwooToken, ERC20, ReentrancyGuard, Ownable, AddressChecksumStringUtil { using ECDSA for bytes32; using Strings for uint256; /// @dev Controls whether or not the deposit/withdraw functionality is enabled bool public isActive = true; /// @dev The percentage of spent virtual AWOO taken as a fee uint256 public awooFeePercentage = 10; /// @dev The Awoo Studios account where fees are sent address public awooStudiosAccount; address[2] private _admins; bool private _adminsSet; /// @dev Keeps track of which contracts are explicitly allowed to add virtual AWOO to a holder's address, spend from it, or /// in the future, mint ERC-20 tokens mapping(address => bool) private _authorizedContracts; /// @dev Keeps track of each holders virtual AWOO balance mapping(address => uint256) private _virtualBalance; /// @dev Keeps track of nonces used for spending events to prevent double spends mapping(string => bool) private _usedNonces; event AuthorizedContractAdded(address contractAddress, address addedBy); event AuthorizedContractRemoved(address contractAddress, address removedBy); event VirtualAwooSpent(address spender, uint256 amount); constructor(address awooAccount) ERC20("Awoo Token", "AWOO") { require(awooAccount != address(0), "Invalid awooAccount"); awooStudiosAccount = awooAccount; } /// @notice Allows an authorized contract to mint $AWOO /// @param account The account to receive the minted $AWOO tokens /// @param amount The amount of $AWOO to mint function mint(address account, uint256 amount) external nonReentrant onlyAuthorizedContract { require(account != address(0), "Cannot mint to the zero address"); require(amount > 0, "Amount cannot be zero"); _mint(account, amount); } /// @notice Allows the owner or an admin to add authorized contracts /// @param contractAddress The address of the contract to authorize function addAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin { require(isContract(contractAddress), "Not a contract address"); _authorizedContracts[contractAddress] = true; emit AuthorizedContractAdded(contractAddress, _msgSender()); } /// @notice Allows the owner or an admin to remove authorized contracts /// @param contractAddress The address of the contract to revoke authorization for function removeAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin { _authorizedContracts[contractAddress] = false; emit AuthorizedContractRemoved(contractAddress, _msgSender()); } /// @notice Exchanges virtual AWOO for ERC-20 $AWOO /// @param amount The amount of virtual AWOO to withdraw function withdraw(uint256 amount) external whenActive hasBalance(amount, _virtualBalance[_msgSender()]) nonReentrant { _mint(_msgSender(), amount); _virtualBalance[_msgSender()] -= amount; } /// @notice Exchanges ERC-20 $AWOO for virtual AWOO to be used in the Awoo Studios ecosystem /// @param amount The amount of $AWOO to deposit function deposit(uint256 amount) external whenActive hasBalance(amount, balanceOf(_msgSender())) nonReentrant { _burn(_msgSender(), amount); _virtualBalance[_msgSender()] += amount; } /// @notice Returns the amount of virtual AWOO held by the specified address /// @param account The holder account to check function balanceOfVirtual(address account) external view returns(uint256) { return _virtualBalance[account]; } /// @notice Returns the amount of ERC-20 $AWOO held by the specified address /// @param account The holder account to check function totalBalanceOf(address account) external view returns(uint256) { return _virtualBalance[account] + balanceOf(account); } /// @notice Allows authorized contracts to increase a holders virtual AWOO /// @param account The account to increase /// @param amount The amount of virtual AWOO to increase the account by function increaseVirtualBalance(address account, uint256 amount) external onlyAuthorizedContract { _virtualBalance[account] += amount; } /// @notice Allows authorized contracts to faciliate the spending of virtual AWOO, and fees to be paid to /// Awoo Studios. /// @notice Only amounts that have been signed and verified by the token holder can be spent /// @param hash The hash of the message displayed to and signed by the holder /// @param sig The signature of the messages that was signed by the holder /// @param nonce The unique code used to prevent double spends /// @param account The account of the holder to debit /// @param amount The amount of virtual AWOO to debit function spendVirtualAwoo(bytes32 hash, bytes memory sig, string calldata nonce, address account, uint256 amount) external onlyAuthorizedContract hasBalance(amount, _virtualBalance[account]) nonReentrant { require(_usedNonces[nonce] == false, "Duplicate nonce"); require(matchAddresSigner(account, hash, sig), "Message signer mismatch"); // Make sure that the spend request was authorized (signed) by the holder require(hashTransaction(account, amount) == hash, "Hash check failed"); // Make sure that only the amount authorized by the holder can be spent // debit the holder's virtual AWOO account _virtualBalance[account]-=amount; // Mint the spending fee to the Awoo Studios account _mint(awooStudiosAccount, ((amount * awooFeePercentage)/100)); _usedNonces[nonce] = true; emit VirtualAwooSpent(account, amount); } /// @notice Allows the owner to specify two addresses allowed to administer this contract /// @param adminAddresses A 2 item array of addresses function setAdmins(address[2] calldata adminAddresses) external onlyOwner { require(adminAddresses[0] != address(0) && adminAddresses[1] != address(0), "Invalid admin address"); _admins = adminAddresses; _adminsSet = true; } /// @notice Allows the owner or an admin to activate/deactivate deposit and withdraw functionality /// @notice This will only be used to disable functionality as a worst case scenario /// @param active The value specifiying whether or not deposits/withdraws should be allowed function setActiveState(bool active) external onlyOwnerOrAdmin { isActive = active; } /// @notice Allows the owner to change the account used for collecting spending fees /// @param awooAccount The new account function setAwooStudiosAccount(address awooAccount) external onlyOwner { require(awooAccount != address(0), "Invalid awooAccount"); awooStudiosAccount = awooAccount; } /// @notice Allows the owner to change the spending fee percentage /// @param feePercentage The new fee percentage function setFeePercentage(uint256 feePercentage) external onlyOwner { awooFeePercentage = feePercentage; // We're intentionally allowing the fee percentage to be set to 0%, incase no fees need to be collected } /// @notice Allows the owner to withdraw any Ethereum that was accidentally sent to this contract function rescueEth() external onlyOwner { payable(owner()).transfer(address(this).balance); } /// @dev Derived from @openzeppelin/contracts/utils/Address.sol function isContract(address account) private view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /// @dev Validates the specified account against the account that signed the message function matchAddresSigner(address account, bytes32 hash, bytes memory signature) private pure returns (bool) { return account == hash.recover(signature); } /// @dev Hashes the message we expected the spender to sign so we can compare the hashes to ensure that the owner /// of the specified address signed the same message /// @dev fractional ether unit amounts aren't supported function hashTransaction(address sender, uint256 amount) private pure returns (bytes32) { require(amount == ((amount/1e18)*1e18), "Invalid amount"); // Virtual $AWOO, much like the ERC-20 $AWOO is stored with 18 implied decimal places. // For user-friendliness, when prompting the user to sign the message, the amount is // _displayed_ without the implied decimals, but it is charged with the implied decimals, // so when validating the hash, we have to use the same value we displayed to the user. // This only affects the display value, nothing else amount = amount/1e18; string memory message = string(abi.encodePacked( "As the owner of Ethereum address\r\n", toChecksumString(sender), "\r\nI authorize the spending of ", amount.toString()," virtual $AWOO" )); uint256 messageLength = bytes(message).length; bytes32 hash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n",messageLength.toString(), message ) ); return hash; } modifier onlyAuthorizedContract() { require(_authorizedContracts[_msgSender()], "Sender is not authorized"); _; } modifier whenActive() { require(isActive, "Contract is not active"); _; } modifier hasBalance(uint256 amount, uint256 balance) { require(amount > 0, "Amount cannot be zero"); require(balance >= amount, "Insufficient Balance"); _; } modifier onlyOwnerOrAdmin() { require( _msgSender() == owner() || (_adminsSet && (_msgSender() == _admins[0] || _msgSender() == _admins[1])), "Caller is not the owner or an admin" ); _; } } // File: contracts/AwooClaimingV2.sol pragma solidity 0.8.12; contract AwooClaimingV2 is IAwooClaimingV2, AuthorizedCallerGuard, ReentrancyGuard { uint256 public accrualStart; uint256 public accrualEnd; bool public claimingActive; /// @dev A collection of supported contracts. These are typically ERC-721, with the addition of the tokensOfOwner function. /// @dev These contracts can be deactivated but cannot be re-activated. Reactivating can be done by adding the same /// contract through addSupportedContract SupportedContractDetails[] public supportedContracts; /// @dev Keeps track of the last time a claim was made for each tokenId within the supported contract collection mapping(address => mapping(uint256 => uint256)) public lastClaims; /// @dev Allows the base accrual rates to be overridden on a per-tokenId level to support things like upgrades mapping(address => mapping(uint256 => uint256)) public baseRateTokenOverrides; AwooClaiming public v1ClaimingContract; AwooToken public awooContract; /// @dev Base accrual rates are set a per-day rate so we change them to per-minute to allow for more frequent claiming uint64 private _baseRateDivisor = 1440; /// @dev Faciliates the maintence and functionality related to supportedContracts uint8 private _activeSupportedContractCount; mapping(address => uint8) private _supportedContractIds; event TokensClaimed(address indexed claimedBy, uint256 qty); event ClaimingStatusChanged(bool newStatus, address changedBy); constructor(AwooClaiming v1Contract) { v1ClaimingContract = v1Contract; accrualStart = v1ClaimingContract.accrualStart(); } /// @notice Sets the first version of the claiming contract, which has been replaced with this one /// @param v1Contract A reference to the v1 claiming contract function setV1ClaimingContract(AwooClaiming v1Contract) external onlyOwnerOrAdmin { v1ClaimingContract = v1Contract; accrualStart = v1ClaimingContract.accrualStart(); } /// @notice Determines the amount of accrued virtual AWOO for the specified address, based on the /// base accural rates for each supported contract and how long has elapsed (in minutes) since the /// last claim was made for a give supported contract tokenId /// @param owner The address of the owner/holder of tokens for a supported contract /// @return A collection of accrued virtual AWOO and the tokens it was accrued on for each supported contract, and the total AWOO accrued function getTotalAccruals(address owner) public view returns (AccrualDetails[] memory, uint256) { // Initialize the array length based on the number of _active_ supported contracts AccrualDetails[] memory totalAccruals = new AccrualDetails[](_activeSupportedContractCount); uint256 totalAccrued; uint8 contractCount; // Helps us keep track of the index to use when setting the values for totalAccruals for(uint8 i = 0; i < supportedContracts.length; i++) { SupportedContractDetails memory contractDetails = supportedContracts[i]; if(contractDetails.Active){ contractCount++; // Get an array of tokenIds held by the owner for the supported contract uint256[] memory tokenIds = ISupportedContract(contractDetails.ContractAddress).tokensOfOwner(owner); uint256[] memory accruals = new uint256[](tokenIds.length); uint256 totalAccruedByContract; for (uint16 x = 0; x < tokenIds.length; x++) { uint32 tokenId = uint32(tokenIds[x]); uint256 accrued = getContractTokenAccruals(contractDetails.ContractAddress, tokenId); totalAccruedByContract+=accrued; totalAccrued+=accrued; tokenIds[x] = tokenId; accruals[x] = accrued; } AccrualDetails memory accrual = AccrualDetails(contractDetails.ContractAddress, tokenIds, accruals, totalAccruedByContract); totalAccruals[contractCount-1] = accrual; } } return (totalAccruals, totalAccrued); } /// @notice Claims all virtual AWOO accrued by the message sender, assuming the sender holds any supported contracts tokenIds function claimAll(address holder) external nonReentrant { require(claimingActive, "Claiming is inactive"); require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt"); (AccrualDetails[] memory accruals, uint256 totalAccrued) = getTotalAccruals(holder); require(totalAccrued > 0, "No tokens have been accrued"); for(uint8 i = 0; i < accruals.length; i++){ AccrualDetails memory accrual = accruals[i]; if(accrual.TotalAccrued > 0){ for(uint16 x = 0; x < accrual.TokenIds.length;x++){ // Update the time that this token was last claimed lastClaims[accrual.ContractAddress][accrual.TokenIds[x]] = block.timestamp; } } } // A holder's virtual AWOO balance is stored in the $AWOO ERC-20 contract awooContract.increaseVirtualBalance(holder, totalAccrued); emit TokensClaimed(holder, totalAccrued); } /// @notice Claims the accrued virtual AWOO from the specified supported contract tokenIds /// @param requestedClaims A collection of supported contract addresses and the specific tokenIds to claim from function claim(address holder, ClaimDetails[] calldata requestedClaims) external nonReentrant { require(claimingActive, "Claiming is inactive"); require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt"); uint256 totalClaimed; for(uint8 i = 0; i < requestedClaims.length; i++){ ClaimDetails calldata requestedClaim = requestedClaims[i]; uint8 contractId = _supportedContractIds[requestedClaim.ContractAddress]; if(contractId == 0) revert("Unsupported contract"); SupportedContractDetails memory contractDetails = supportedContracts[contractId-1]; if(!contractDetails.Active) revert("Inactive contract"); for(uint16 x = 0; x < requestedClaim.TokenIds.length; x++){ uint32 tokenId = requestedClaim.TokenIds[x]; address tokenOwner = ISupportedContract(address(contractDetails.ContractAddress)).ownerOf(tokenId); if(tokenOwner != holder) revert("Invalid owner claim attempt"); uint256 claimableAmount = getContractTokenAccruals(contractDetails.ContractAddress, tokenId); if(claimableAmount > 0){ totalClaimed+=claimableAmount; // Update the time that this token was last claimed lastClaims[contractDetails.ContractAddress][tokenId] = block.timestamp; } } } if(totalClaimed > 0){ awooContract.increaseVirtualBalance(holder, totalClaimed); emit TokensClaimed(holder, totalClaimed); } } /// @notice Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId /// @dev To save gas, we don't validate the existence of the token within the specified collection as this is done /// within the claiming functions /// @dev The first time a claim is made in this contract, we use the v1 contract's last claim time so we don't /// accrue based on accruals that were claimed through the v1 contract /// @param contractAddress The contract address of the supported collection /// @param tokenId The id of the token/NFT /// @return The amount of virtual AWOO accrued for the specified token and collection function getContractTokenAccruals(address contractAddress, uint32 tokenId) public view returns(uint256){ uint8 contractId = _supportedContractIds[contractAddress]; if(contractId == 0) revert("Unsupported contract"); SupportedContractDetails memory contractDetails = supportedContracts[contractId-1]; if(!contractDetails.Active) revert("Inactive contract"); uint256 lastClaimTime = lastClaims[contractAddress][tokenId] > 0 ? lastClaims[contractAddress][tokenId] : v1ClaimingContract.lastClaims(contractAddress, tokenId); uint256 accruedUntil = accrualEnd == 0 || block.timestamp < accrualEnd ? block.timestamp : accrualEnd; uint256 baseRate = getContractTokenBaseAccrualRate(contractDetails, tokenId); if (lastClaimTime > 0){ return (baseRate*(accruedUntil-lastClaimTime))/60; } else { return (baseRate*(accruedUntil-accrualStart))/60; } } /// @notice Returns the current base accrual rate for the specified token, taking overrides into account /// @dev This is mostly to support testing /// @param contractDetails The details of the supported contract /// @param tokenId The id of the token/NFT /// @return The base accrual rate function getContractTokenBaseAccrualRate(SupportedContractDetails memory contractDetails, uint32 tokenId ) public view returns(uint256){ return baseRateTokenOverrides[contractDetails.ContractAddress][tokenId] > 0 ? baseRateTokenOverrides[contractDetails.ContractAddress][tokenId] : contractDetails.BaseRate; } /// @notice Allows an authorized contract to increase the base accrual rate for particular NFTs /// when, for example, upgrades for that NFT were purchased /// @param contractAddress The address of the supported contract /// @param tokenId The id of the token from the supported contract whose base accrual rate will be updated /// @param newBaseRate The new accrual base rate function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate) external onlyAuthorizedContract isValidBaseRate(newBaseRate) { require(tokenId > 0, "Invalid tokenId"); uint8 contractId = _supportedContractIds[contractAddress]; require(contractId > 0, "Unsupported contract"); require(supportedContracts[contractId-1].Active, "Inactive contract"); baseRateTokenOverrides[contractAddress][tokenId] = (newBaseRate/_baseRateDivisor); } /// @notice Allows the owner or an admin to set a reference to the $AWOO ERC-20 contract /// @param awooToken An instance of IAwooToken function setAwooTokenContract(AwooToken awooToken) external onlyOwnerOrAdmin { awooContract = awooToken; } /// @notice Allows the owner or an admin to set the date and time at which virtual AWOO accruing will stop /// @notice This will only be used if absolutely necessary and any AWOO that accrued before the end date will still be claimable /// @param timestamp The Epoch time at which accrual should end function setAccrualEndTimestamp(uint256 timestamp) external onlyOwnerOrAdmin { accrualEnd = timestamp; } /// @notice Allows the owner or an admin to add a contract whose tokens are eligible to accrue virtual AWOO /// @param contractAddress The contract address of the collection (typically ERC-721, with the addition of the tokensOfOwner function) /// @param baseRate The base accrual rate in wei units function addSupportedContract(address contractAddress, uint256 baseRate) public onlyOwnerOrAdmin isValidBaseRate(baseRate) { require(_isContract(contractAddress), "Invalid contractAddress"); require(_supportedContractIds[contractAddress] == 0, "Contract already supported"); supportedContracts.push(SupportedContractDetails(contractAddress, baseRate/_baseRateDivisor, true)); _supportedContractIds[contractAddress] = uint8(supportedContracts.length); _activeSupportedContractCount++; } /// @notice Allows the owner or an admin to deactivate a supported contract so it no longer accrues virtual AWOO /// @param contractAddress The contract address that should be deactivated function deactivateSupportedContract(address contractAddress) external onlyOwnerOrAdmin { require(_supportedContractIds[contractAddress] > 0, "Unsupported contract"); supportedContracts[_supportedContractIds[contractAddress]-1].Active = false; supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = 0; _supportedContractIds[contractAddress] = 0; _activeSupportedContractCount--; } /// @notice Allows the owner or an admin to set the base accrual rate for a support contract /// @param contractAddress The address of the supported contract /// @param baseRate The new base accrual rate in wei units function setBaseRate(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) { require(_supportedContractIds[contractAddress] > 0, "Unsupported contract"); supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = baseRate/_baseRateDivisor; } /// @notice Allows the owner or an admin to activate/deactivate claiming ability /// @param active The value specifiying whether or not claiming should be allowed function setClaimingActive(bool active) external onlyOwnerOrAdmin { claimingActive = active; emit ClaimingStatusChanged(active, _msgSender()); } /// @dev To minimize the amount of unit conversion we have to do for comparing $AWOO (ERC-20) to virtual AWOO, we store /// virtual AWOO with 18 implied decimal places, so this modifier prevents us from accidentally using the wrong unit /// for base rates. For example, if holders of FangGang NFTs accrue at a rate of 1000 AWOO per fang, pre day, then /// the base rate should be 1000000000000000000000 modifier isValidBaseRate(uint256 baseRate) { require(baseRate >= 1 ether, "Base rate must be in wei units"); _; } } // File: contracts/AwooClaimingV3.sol pragma solidity 0.8.12; contract AwooClaimingV3 is IAwooClaimingV2, AuthorizedCallerGuard, ReentrancyGuard { uint256 public accrualStart; uint256 public accrualEnd; bool public claimingActive = false; /// @dev A collection of supported contracts. These are typically ERC-721, with the addition of the tokensOfOwner function. /// @dev These contracts can be deactivated but cannot be re-activated. Reactivating can be done by adding the same /// contract through addSupportedContract SupportedContractDetails[] public supportedContracts; /// @dev Keeps track of the last time a claim was made for each tokenId within the supported contract collection // contractAddress => (tokenId, lastClaimTimestamp) mapping(address => mapping(uint256 => uint48)) public lastClaims; /// @dev Allows the base accrual rates to be overridden on a per-tokenId level to support things like upgrades mapping(address => mapping(uint256 => uint256)) public baseRateTokenOverrides; // contractAddress => (tokenId, accruedAmount) mapping(address => mapping(uint256 => uint256)) public unclaimedSnapshot; AwooClaiming public v1ClaimingContract; AwooClaimingV2 public v2ClaimingContract; AwooToken public awooContract; /// @dev Base accrual rates are set a per-day rate so we change them to per-minute to allow for more frequent claiming uint64 private _baseRateDivisor = 1440; /// @dev Faciliates the maintence and functionality related to supportedContracts uint8 private _activeSupportedContractCount; mapping(address => uint8) private _supportedContractIds; event TokensClaimed(address indexed claimedBy, uint256 qty); event ClaimingStatusChanged(bool newStatus, address changedBy); constructor(AwooToken awooTokenContract, AwooClaimingV2 v2Contract, AwooClaiming v1Contract) { awooContract = awooTokenContract; v2ClaimingContract = v2Contract; accrualStart = v2ClaimingContract.accrualStart(); v1ClaimingContract = v1Contract; } /// @notice Sets the previous versions of the claiming contracts, which have been replaced with this one function setContracts(AwooClaimingV2 v2Contract, AwooClaiming v1Contract) external onlyOwnerOrAdmin { v2ClaimingContract = v2Contract; accrualStart = v2ClaimingContract.accrualStart(); v1ClaimingContract = v1Contract; } /// @notice Determines the amount of accrued virtual AWOO for the specified address, based on the /// base accural rates for each supported contract and how long has elapsed (in minutes) since the /// last claim was made for a give supported contract tokenId /// @param owner The address of the owner/holder of tokens for a supported contract /// @return A collection of accrued virtual AWOO and the tokens it was accrued on for each supported contract, and the total AWOO accrued function getTotalAccruals(address owner) public view returns (AccrualDetails[] memory, uint256) { // Initialize the array length based on the number of _active_ supported contracts AccrualDetails[] memory totalAccruals = new AccrualDetails[](_activeSupportedContractCount); uint256 totalAccrued; uint8 contractCount; // Helps us keep track of the index to use when setting the values for totalAccruals for(uint8 i = 0; i < supportedContracts.length; i++) { SupportedContractDetails memory contractDetails = supportedContracts[i]; if(contractDetails.Active){ contractCount++; // Get an array of tokenIds held by the owner for the supported contract uint256[] memory tokenIds = ISupportedContract(contractDetails.ContractAddress).tokensOfOwner(owner); uint256[] memory accruals = new uint256[](tokenIds.length); uint256 totalAccruedByContract; for (uint16 x = 0; x < tokenIds.length; x++) { uint256 tokenId = tokenIds[x]; uint256 accrued = getContractTokenAccruals(contractDetails.ContractAddress, tokenId); totalAccruedByContract+=accrued; totalAccrued+=accrued; tokenIds[x] = tokenId; accruals[x] = accrued; } AccrualDetails memory accrual = AccrualDetails(contractDetails.ContractAddress, tokenIds, accruals, totalAccruedByContract); totalAccruals[contractCount-1] = accrual; } } return (totalAccruals, totalAccrued); } /// @notice Claims all virtual AWOO accrued by the message sender, assuming the sender holds any supported contracts tokenIds function claimAll(address holder) external nonReentrant { require(claimingActive, "Claiming is inactive"); require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt"); (AccrualDetails[] memory accruals, uint256 totalAccrued) = getTotalAccruals(holder); require(totalAccrued > 0, "No tokens have been accrued"); for(uint8 i = 0; i < accruals.length; i++){ AccrualDetails memory accrual = accruals[i]; if(accrual.TotalAccrued > 0){ for(uint16 x = 0; x < accrual.TokenIds.length;x++){ // Update the time that this token was last claimed lastClaims[accrual.ContractAddress][accrual.TokenIds[x]] = uint48(block.timestamp); // Any amount from the unclaimed snapshot are now claimed because they were returned by getContractTokenAccruals // so dump it delete unclaimedSnapshot[accrual.ContractAddress][accrual.TokenIds[x]]; } } } // A holder's virtual AWOO balance is stored in the $AWOO ERC-20 contract awooContract.increaseVirtualBalance(holder, totalAccrued); emit TokensClaimed(holder, totalAccrued); } /// @notice Claims the accrued virtual AWOO from the specified supported contract tokenIds /// @param requestedClaims A collection of supported contract addresses and the specific tokenIds to claim from function claim(address holder, ClaimDetails[] calldata requestedClaims) external nonReentrant { require(claimingActive, "Claiming is inactive"); require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt"); uint256 totalClaimed; for(uint8 i = 0; i < requestedClaims.length; i++){ ClaimDetails calldata requestedClaim = requestedClaims[i]; uint8 contractId = _supportedContractIds[requestedClaim.ContractAddress]; if(contractId == 0) revert("Unsupported contract"); SupportedContractDetails memory contractDetails = supportedContracts[contractId-1]; if(!contractDetails.Active) revert("Inactive contract"); for(uint16 x = 0; x < requestedClaim.TokenIds.length; x++){ uint32 tokenId = requestedClaim.TokenIds[x]; address tokenOwner = ISupportedContract(address(contractDetails.ContractAddress)).ownerOf(tokenId); if(tokenOwner != holder) revert("Invalid owner claim attempt"); uint256 claimableAmount = getContractTokenAccruals(contractDetails.ContractAddress, tokenId); if(claimableAmount > 0){ totalClaimed+=claimableAmount; // Update the time that this token was last claimed lastClaims[contractDetails.ContractAddress][tokenId] = uint48(block.timestamp); // Any amount from the unclaimed snapshot are now claimed because they were returned by getContractTokenAccruals // so dump it delete unclaimedSnapshot[contractDetails.ContractAddress][tokenId]; } } } if(totalClaimed > 0){ awooContract.increaseVirtualBalance(holder, totalClaimed); emit TokensClaimed(holder, totalClaimed); } } /// @notice Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId /// @dev To save gas, we don't validate the existence of the token within the specified collection as this is done /// within the claiming functions /// @dev The first time a claim is made in this contract, we use the v1 contract's last claim time so we don't /// accrue based on accruals that were claimed through the v1 contract /// @param contractAddress The contract address of the supported collection /// @param tokenId The id of the token/NFT /// @return The amount of virtual AWOO accrued for the specified token and collection function getContractTokenAccruals(address contractAddress, uint256 tokenId) public view returns(uint256){ uint8 contractId = _supportedContractIds[contractAddress]; if(contractId == 0) revert("Unsupported contract"); SupportedContractDetails memory contractDetails = supportedContracts[contractId-1]; if(!contractDetails.Active) revert("Inactive contract"); return getContractTokenAccruals(contractDetails, tokenId, uint48(block.timestamp)); } /// @notice Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId, at the point in time specified /// @dev To save gas, we don't validate the existence of the token within the specified collection as this is done /// within the claiming functions /// @dev The first time a claim is made in this contract, we use the v1 contract's last claim time so we don't /// accrue based on accruals that were claimed through the v1 contract /// @param contractDetails The contract details of the supported collection /// @param tokenId The id of the token/NFT /// @param accruedUntilTimestamp The timestamp to calculate accruals from /// @return The amount of virtual AWOO accrued for the specified token and collection function getContractTokenAccruals(SupportedContractDetails memory contractDetails, uint256 tokenId, uint48 accruedUntilTimestamp ) private view returns(uint256){ uint48 lastClaimTime = getLastClaimTime(contractDetails.ContractAddress, tokenId); uint256 accruedUntil = accrualEnd == 0 || accruedUntilTimestamp < accrualEnd ? accruedUntilTimestamp : accrualEnd; uint256 existingSnapshotAmount = unclaimedSnapshot[contractDetails.ContractAddress][tokenId]; uint256 baseRate = getContractTokenBaseAccrualRate(contractDetails, tokenId); if (lastClaimTime > 0){ return existingSnapshotAmount + ((baseRate*(accruedUntil-lastClaimTime))/60); } else { return existingSnapshotAmount + ((baseRate*(accruedUntil-accrualStart))/60); } } function getLastClaimTime(address contractAddress, uint256 tokenId) public view returns(uint48){ uint48 lastClaim = lastClaims[contractAddress][tokenId]; // If a claim has already been made through this contract, return the time of that claim if(lastClaim > 0) { return lastClaim; } // If not claims have been made through this contract, check V2 lastClaim = uint48(v2ClaimingContract.lastClaims(contractAddress, tokenId)); if(lastClaim > 0) { return lastClaim; } // If not claims have been made through the V2 contract, check the OG return uint48(v1ClaimingContract.lastClaims(contractAddress, tokenId)); } /// @notice Returns the current base accrual rate for the specified token, taking overrides into account /// @dev This is mostly to support testing /// @param contractDetails The details of the supported contract /// @param tokenId The id of the token/NFT /// @return The base accrual rate function getContractTokenBaseAccrualRate(SupportedContractDetails memory contractDetails, uint256 tokenId ) public view returns(uint256){ return baseRateTokenOverrides[contractDetails.ContractAddress][tokenId] > 0 ? baseRateTokenOverrides[contractDetails.ContractAddress][tokenId] : contractDetails.BaseRate; } /// @notice Allows an authorized contract to increase the base accrual rate for particular NFTs /// when, for example, upgrades for that NFT were purchased /// @param contractAddress The address of the supported contract /// @param tokenId The id of the token from the supported contract whose base accrual rate will be updated /// @param newBaseRate The new accrual base rate function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate ) external onlyAuthorizedContract isValidBaseRate(newBaseRate) { require(tokenId > 0, "Invalid tokenId"); uint8 contractId = _supportedContractIds[contractAddress]; require(contractId > 0, "Unsupported contract"); require(supportedContracts[contractId-1].Active, "Inactive contract"); // Before overriding the accrual rate, take a snapshot of what the current unclaimed amount is // so that when `claim` or `claimAll` is called, the snapshot amount will be included so // it doesn't get lost // @dev IMPORTANT: The snapshot must be taken _before_ baseRateTokenOverrides is set unclaimedSnapshot[contractAddress][tokenId] = getContractTokenAccruals(contractAddress, tokenId); lastClaims[contractAddress][tokenId] = uint48(block.timestamp); baseRateTokenOverrides[contractAddress][tokenId] = (newBaseRate/_baseRateDivisor); } /// @notice Allows an authorized individual to manually create point-in-time snapshots of AWOO that /// was accrued up until a particular point in time. This is only necessary to correct a bug in the /// V2 claiming contract that caused unclaimed AWOO to double when the base rates were overridden, /// rather than accruing with the new rate from that point in time function fixPreAccrualOverrideSnapshot(address contractAddress, uint256[] calldata tokenIds, uint48[] calldata accruedUntilTimestamps ) external onlyOwnerOrAdmin { require(tokenIds.length == accruedUntilTimestamps.length, "Array length mismatch"); uint8 contractId = _supportedContractIds[contractAddress]; SupportedContractDetails memory contractDetails = supportedContracts[contractId-1]; for(uint16 i; i < tokenIds.length; i++) { if(getLastClaimTime(contractAddress, tokenIds[i]) < accruedUntilTimestamps[i]) { unclaimedSnapshot[contractAddress][tokenIds[i]] = getContractTokenAccruals(contractDetails, tokenIds[i], accruedUntilTimestamps[i]); lastClaims[contractAddress][tokenIds[i]] = accruedUntilTimestamps[i]; } } } /// @notice Allows the owner or an admin to set a reference to the $AWOO ERC-20 contract /// @param awooToken An instance of IAwooToken function setAwooTokenContract(AwooToken awooToken) external onlyOwnerOrAdmin { awooContract = awooToken; } /// @notice Allows the owner or an admin to set the date and time at which virtual AWOO accruing will stop /// @notice This will only be used if absolutely necessary and any AWOO that accrued before the end date will still be claimable /// @param timestamp The Epoch time at which accrual should end function setAccrualEndTimestamp(uint256 timestamp) external onlyOwnerOrAdmin { accrualEnd = timestamp; } /// @notice Allows the owner or an admin to add a contract whose tokens are eligible to accrue virtual AWOO /// @param contractAddress The contract address of the collection (typically ERC-721, with the addition of the tokensOfOwner function) /// @param baseRate The base accrual rate in wei units function addSupportedContract(address contractAddress, uint256 baseRate) public onlyOwnerOrAdmin isValidBaseRate(baseRate) { require(_isContract(contractAddress), "Invalid contractAddress"); require(_supportedContractIds[contractAddress] == 0, "Contract already supported"); supportedContracts.push(SupportedContractDetails(contractAddress, baseRate/_baseRateDivisor, true)); _supportedContractIds[contractAddress] = uint8(supportedContracts.length); _activeSupportedContractCount++; } /// @notice Allows the owner or an admin to deactivate a supported contract so it no longer accrues virtual AWOO /// @param contractAddress The contract address that should be deactivated function deactivateSupportedContract(address contractAddress) external onlyOwnerOrAdmin { require(_supportedContractIds[contractAddress] > 0, "Unsupported contract"); supportedContracts[_supportedContractIds[contractAddress]-1].Active = false; supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = 0; _supportedContractIds[contractAddress] = 0; _activeSupportedContractCount--; } /// @notice Allows the owner or an admin to set the base accrual rate for a support contract /// @param contractAddress The address of the supported contract /// @param baseRate The new base accrual rate in wei units function setBaseRate(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) { require(_supportedContractIds[contractAddress] > 0, "Unsupported contract"); supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = baseRate/_baseRateDivisor; } /// @notice Allows the owner or an admin to activate/deactivate claiming ability /// @param active The value specifiying whether or not claiming should be allowed function setClaimingActive(bool active) external onlyOwnerOrAdmin { claimingActive = active; emit ClaimingStatusChanged(active, _msgSender()); } /// @dev To minimize the amount of unit conversion we have to do for comparing $AWOO (ERC-20) to virtual AWOO, we store /// virtual AWOO with 18 implied decimal places, so this modifier prevents us from accidentally using the wrong unit /// for base rates. For example, if holders of FangGang NFTs accrue at a rate of 1000 AWOO per fang, pre day, then /// the base rate should be 1000000000000000000000 modifier isValidBaseRate(uint256 baseRate) { require(baseRate >= 1 ether, "Base rate must be in wei units"); _; } }
Claims all virtual AWOO accrued by the message sender, assuming the sender holds any supported contracts tokenIds Update the time that this token was last claimed Any amount from the unclaimed snapshot are now claimed because they were returned by getContractTokenAccruals so dump it
function claimAll(address holder) external nonReentrant { require(claimingActive, "Claiming is inactive"); require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt"); (AccrualDetails[] memory accruals, uint256 totalAccrued) = getTotalAccruals(holder); require(totalAccrued > 0, "No tokens have been accrued"); for(uint8 i = 0; i < accruals.length; i++){ AccrualDetails memory accrual = accruals[i]; if(accrual.TotalAccrued > 0){ for(uint16 x = 0; x < accrual.TokenIds.length;x++){ lastClaims[accrual.ContractAddress][accrual.TokenIds[x]] = uint48(block.timestamp); delete unclaimedSnapshot[accrual.ContractAddress][accrual.TokenIds[x]]; } } } emit TokensClaimed(holder, totalAccrued); }
10,771,958
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; contract WhiteListManager { event WhiteListAccount(address indexed operator, address indexed account, bool approved); event SetMerkleRoot(address operator, bytes32 merkleRoot); event JoinWithMerkle(address operator, uint256 indexed index, address indexed account); /// @notice EIP-712 related variables and functions. string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; bytes32 private constant APPROVAL_SIGNATURE_HASH = keccak256("SetWhitelisting(address account,bool approved,uint256 deadline)"); bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; mapping(address => mapping(address => bool)) public whitelistedAccounts; /// @notice Merkle root variables. mapping(address => bytes32) public merkleRoot; /// @notice Packed array of booleans. mapping(address => mapping(uint256 => uint256)) internal whitelistedBitMap; function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32 domainSeperator) { domainSeperator = keccak256(abi.encode(DOMAIN_SEPARATOR_SIGNATURE_HASH, keccak256("WhiteListManager"), chainId, address(this))); } function DOMAIN_SEPARATOR() public view returns (bytes32 domainSeperator) { domainSeperator = block.chainid == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid); } constructor() { _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = block.chainid); } function whitelistAccount(address user, bool approved) external { _whitelistAccount(msg.sender, user, approved); } function _whitelistAccount( address operator, address account, bool approved ) private { whitelistedAccounts[operator][account] = approved; emit WhiteListAccount(operator, account, approved); } /// @notice Approves or revokes whitelisting for accounts. /// @param operator The address of the operator that approves or revokes access. /// @param account The address who gains or loses access. /// @param approved If 'true', approves access - if 'false', revokes access. /// @param deadline 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 setWhitelisting( address operator, address account, bool approved, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { // @dev Checks: require(account != address(0), "ACCOUNT_NOT_SET"); // - also, ecrecover returns address(0) on failure. So we check this, even if the modifier should prevent it: require(operator != address(0), "OPERATOR_NULL"); require(deadline >= block.timestamp && deadline <= (block.timestamp + 1 weeks), "EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, DOMAIN_SEPARATOR(), keccak256(abi.encode(APPROVAL_SIGNATURE_HASH, account, approved, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress == operator, "INVALID_SIGNATURE"); _whitelistAccount(operator, account, approved); } /// **** WHITELISTING /// @dev Adapted from OpenZeppelin utilities and Uniswap merkle distributor. function isWhitelisted(address operator, uint256 index) public view returns (bool success) { uint256 whitelistedWordIndex = index / 256; uint256 whitelistedBitIndex = index % 256; uint256 claimedWord = whitelistedBitMap[operator][whitelistedWordIndex]; uint256 mask = (1 << whitelistedBitIndex); success = claimedWord & mask == mask; } function joinWhitelist( address operator, uint256 index, address account, bytes32[] calldata merkleProof ) external { require(!isWhitelisted(operator, index), "CLAIMED"); bytes32 node = keccak256(abi.encodePacked(index, account)); bytes32 computedHash = node; for (uint256 i = 0; i < merkleProof.length; i++) { bytes32 proofElement = merkleProof[i]; if (computedHash <= proofElement) { // @dev Hash(current computed hash + current element of the proof). computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // @dev Hash(current element of the proof + current computed hash). computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // @dev Check if the computed hash (root) is equal to the provided root. require(computedHash == merkleRoot[operator], "NOT_ROOTED"); uint256 whitelistedWordIndex = index / 256; uint256 whitelistedBitIndex = index % 256; whitelistedBitMap[operator][whitelistedWordIndex] = whitelistedBitMap[operator][whitelistedWordIndex] | (1 << whitelistedBitIndex); _whitelistAccount(operator, account, true); emit JoinWithMerkle(operator, index, account); } function setMerkleRoot(bytes32 _merkleRoot) external { // @dev Set the new merkle root. merkleRoot[msg.sender] = _merkleRoot; emit SetMerkleRoot(msg.sender, _merkleRoot); } }
Set the new merkle root.
function setMerkleRoot(bytes32 _merkleRoot) external { merkleRoot[msg.sender] = _merkleRoot; emit SetMerkleRoot(msg.sender, _merkleRoot); }
908,140
/** *Mankind environment coin */ pragma solidity ^0.4.23; /** * @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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ 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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract KECToken is IERC20{ using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) private _blacklist; string public name = "Mankind Environment Coin"; string public symbol = "KEC"; uint public decimals = 18; uint private _totalSupply = 5000000*10**18; address public owner; constructor (address _owner) public{ owner = _owner; _balances[_owner] = _totalSupply; } modifier onlyOwner() { require(msg.sender == owner); _; } function addBlacklist(address account) onlyOwner() public{ _blacklist[account] = true; } function removeBlacklist(address account) onlyOwner() public{ _blacklist[account] = false; } function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return _balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address spender ) public view returns (uint256) { return _allowed[_owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); require(_blacklist[msg.sender] != true && _blacklist[to] != true); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); require(_blacklist[msg.sender] != true && _blacklist[spender] != true); require(value == 0 || _allowed[msg.sender][spender] == 0); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @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 */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); require(_blacklist[to] != true && _blacklist[from] != true); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); require(_blacklist[msg.sender] != true && _blacklist[spender] != true); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); require(_blacklist[msg.sender] != true && _blacklist[spender] != true); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } }
Gets the balance of the specified address. _owner The address to query the balance of. return An uint256 representing the amount owned by the passed address./
function balanceOf(address _owner) public view returns (uint256) { return _balances[_owner]; }
6,401,886
./partial_match/42/0xAc8b3F4E381Ae24467cBeCA803214360481f7812/sources/ArbitrableTokenList.sol
Returns the contribution value and remainder from available ETH and required amount. _available The amount of ETH available for the contribution. _requiredAmount The amount of ETH required for the contribution. return taken The amount of ETH taken. return remainder The amount of ETH left from the contribution./
function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) remainder = _available - _requiredAmount; return (_requiredAmount, remainder); }
8,958,689
./full_match/1/0x11a022822aDCC66111F9b2DAf5B2E892f90d95b4/sources/contracts/BasicDEX.sol
refund dust eth, if any
function swapETHForExactTokens(uint256 amountOut, address[] calldata path, address to, uint256 deadline) external virtual override payable ensure(deadline) onlyAllowedAssets(path) returns (uint256[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = DEXLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); amounts = _getAmountsOutWithFee(path, amounts[0], true); assert(IWETH(WETH).transfer(DEXLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); }
4,884,431
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; /** * @dev Define interface verifier */ interface VerifierRollupInterface { function verifyProof( uint256[2] calldata proofA, uint256[2][2] calldata proofB, uint256[2] calldata proofC, uint256[1] calldata input ) external view returns (bool); } /** * @dev Define interface verifier */ interface VerifierWithdrawInterface { function verifyProof( uint256[2] calldata proofA, uint256[2][2] calldata proofB, uint256[2] calldata proofC, uint256[1] calldata input ) external view returns (bool); } /** * @dev Litex will run an auction to incentivise efficiency in coordinators, * meaning that they need to be very effective and include as many transactions * as they can in the slots in order to compensate for their bidding costs, gas * costs and operations costs.The general porpouse of this smartcontract is to * define the rules to coordinate this auction where the bids will be placed * only in LXT utility token. */ interface ILitexAuctionProtocol { /** * @notice Getter of the current `_slotDeadline` * @return The `_slotDeadline` value */ function getSlotDeadline() external view returns (uint8); /** * @notice Allows to change the `_slotDeadline` if it's called by the owner * @param newDeadline new `_slotDeadline` * Events: `NewSlotDeadline` */ function setSlotDeadline(uint8 newDeadline) external; /** * @notice Getter of the current `_openAuctionSlots` * @return The `_openAuctionSlots` value */ function getOpenAuctionSlots() external view returns (uint16); /** * @notice Allows to change the `_openAuctionSlots` if it's called by the owner * @dev Max newOpenAuctionSlots = 65536 slots * @param newOpenAuctionSlots new `_openAuctionSlots` * Events: `NewOpenAuctionSlots` * Note: the governance could set this parameter equal to `ClosedAuctionSlots`, this means that it can prevent bids * from being made and that only the boot coordinator can forge */ function setOpenAuctionSlots(uint16 newOpenAuctionSlots) external; /** * @notice Getter of the current `_closedAuctionSlots` * @return The `_closedAuctionSlots` value */ function getClosedAuctionSlots() external view returns (uint16); /** * @notice Allows to change the `_closedAuctionSlots` if it's called by the owner * @dev Max newClosedAuctionSlots = 65536 slots * @param newClosedAuctionSlots new `_closedAuctionSlots` * Events: `NewClosedAuctionSlots` * Note: the governance could set this parameter equal to `OpenAuctionSlots`, this means that it can prevent bids * from being made and that only the boot coordinator can forge */ function setClosedAuctionSlots(uint16 newClosedAuctionSlots) external; /** * @notice Getter of the current `_outbidding` * @return The `_outbidding` value */ function getOutbidding() external view returns (uint16); /** * @notice Allows to change the `_outbidding` if it's called by the owner * @dev newOutbidding between 0.00% and 655.36% * @param newOutbidding new `_outbidding` * Events: `NewOutbidding` */ function setOutbidding(uint16 newOutbidding) external; /** * @notice Getter of the current `_allocationRatio` * @return The `_allocationRatio` array */ function getAllocationRatio() external view returns (uint16[3] memory); /** * @notice Allows to change the `_allocationRatio` array if it's called by the owner * @param newAllocationRatio new `_allocationRatio` uint8[3] array * Events: `NewAllocationRatio` */ function setAllocationRatio(uint16[3] memory newAllocationRatio) external; /** * @notice Getter of the current `_donationAddress` * @return The `_donationAddress` */ function getDonationAddress() external view returns (address); /** * @notice Allows to change the `_donationAddress` if it's called by the owner * @param newDonationAddress new `_donationAddress` * Events: `NewDonationAddress` */ function setDonationAddress(address newDonationAddress) external; /** * @notice Getter of the current `_bootCoordinator` * @return The `_bootCoordinator` */ function getBootCoordinator() external view returns (address); /** * @notice Allows to change the `_bootCoordinator` if it's called by the owner * @param newBootCoordinator new `_bootCoordinator` uint8[3] array * Events: `NewBootCoordinator` */ function setBootCoordinator( address newBootCoordinator, string memory newBootCoordinatorURL ) external; /** * @notice Allows to change the change the min bid for an slotSet if it's called by the owner. * @dev If an slotSet has the value of 0 it's considered decentralized, so the minbid cannot be modified * @param slotSet the slotSet to update * @param newInitialMinBid the minBid * Events: `NewDefaultSlotSetBid` */ function changeDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid) external; /** * @notice Allows to register a new coordinator * @dev The `msg.sender` will be considered the `bidder`, who can change the forger address and the url * @param forger the address allowed to forger batches * @param coordinatorURL endopoint for this coordinator * Events: `NewCoordinator` */ function setCoordinator(address forger, string memory coordinatorURL) external; /** * @notice Function to process a single bid * @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to * make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes * @param amount the amount of tokens that have been sent * @param slot the slot for which the caller is bidding * @param bidAmount the amount of the bidding */ function processBid( uint128 amount, uint128 slot, uint128 bidAmount, bytes calldata permit ) external; /** * @notice function to process a multi bid * @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to * make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes * @param amount the amount of tokens that have been sent * @param startingSlot the first slot to bid * @param endingSlot the last slot to bid * @param slotSets the set of slots to which the coordinator wants to bid * @param maxBid the maximum bid that is allowed * @param minBid the minimum that you want to bid */ function processMultiBid( uint128 amount, uint128 startingSlot, uint128 endingSlot, bool[6] memory slotSets, uint128 maxBid, uint128 minBid, bytes calldata permit ) external; /** * @notice function to process the forging * @param forger the address of the coodirnator's forger * Events: `NewForgeAllocated` and `NewForge` */ function forge(address forger) external; /** * @notice function to know if a certain address can forge into a certain block * @param forger the address of the coodirnator's forger * @param blockNumber block number to check * @return a bool true in case it can forge, false otherwise */ function canForge(address forger, uint256 blockNumber) external view returns (bool); } /** * @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) { 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; } } /** * @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 a proxied contract can't have 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 {UpgradeableProxy-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. */ 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() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } /** * @dev Interface poseidon hash function 2 elements */ contract PoseidonUnit2 { function poseidon(uint256[2] memory) public pure returns (uint256) {} } /** * @dev Interface poseidon hash function 3 elements */ contract PoseidonUnit3 { function poseidon(uint256[3] memory) public pure returns (uint256) {} } /** * @dev Interface poseidon hash function 4 elements */ contract PoseidonUnit4 { function poseidon(uint256[4] memory) public pure returns (uint256) {} } /** * @dev Rollup helper functions */ contract LitexHelpers is Initializable { PoseidonUnit2 _insPoseidonUnit2; PoseidonUnit3 _insPoseidonUnit3; PoseidonUnit4 _insPoseidonUnit4; uint256 private constant _WORD_SIZE = 32; // bytes32 public constant EIP712DOMAIN_HASH = // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") bytes32 public constant EIP712DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; // bytes32 public constant NAME_HASH = // keccak256("Litex Network") bytes32 public constant NAME_HASH = 0xbe287413178bfeddef8d9753ad4be825ae998706a6dabff23978b59dccaea0ad; // bytes32 public constant VERSION_HASH = // keccak256("1") bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; // bytes32 public constant AUTHORISE_TYPEHASH = // keccak256("Authorise(string Provider,string Authorisation,bytes32 BJJKey)"); bytes32 public constant AUTHORISE_TYPEHASH = 0xafd642c6a37a2e6887dc4ad5142f84197828a904e53d3204ecb1100329231eaa; // bytes32 public constant LITEX_NETWORK_HASH = keccak256(bytes("Litex Network")), bytes32 public constant LITEX_NETWORK_HASH = 0xbe287413178bfeddef8d9753ad4be825ae998706a6dabff23978b59dccaea0ad; // bytes32 public constant ACCOUNT_CREATION_HASH = keccak256(bytes("Account creation")), bytes32 public constant ACCOUNT_CREATION_HASH = 0xff946cf82975b1a2b6e6d28c9a76a4b8d7a1fd0592b785cb92771933310f9ee7; /** * @dev Load poseidon smart contract * @param _poseidon2Elements Poseidon contract address for 2 elements * @param _poseidon3Elements Poseidon contract address for 3 elements * @param _poseidon4Elements Poseidon contract address for 4 elements */ function _initializeHelpers( address _poseidon2Elements, address _poseidon3Elements, address _poseidon4Elements ) internal initializer { _insPoseidonUnit2 = PoseidonUnit2(_poseidon2Elements); _insPoseidonUnit3 = PoseidonUnit3(_poseidon3Elements); _insPoseidonUnit4 = PoseidonUnit4(_poseidon4Elements); } /** * @dev Hash poseidon for 2 elements * @param inputs Poseidon input array of 2 elements * @return Poseidon hash */ function _hash2Elements(uint256[2] memory inputs) internal view returns (uint256) { return _insPoseidonUnit2.poseidon(inputs); } /** * @dev Hash poseidon for 3 elements * @param inputs Poseidon input array of 3 elements * @return Poseidon hash */ function _hash3Elements(uint256[3] memory inputs) internal view returns (uint256) { return _insPoseidonUnit3.poseidon(inputs); } /** * @dev Hash poseidon for 4 elements * @param inputs Poseidon input array of 4 elements * @return Poseidon hash */ function _hash4Elements(uint256[4] memory inputs) internal view returns (uint256) { return _insPoseidonUnit4.poseidon(inputs); } /** * @dev Hash poseidon for sparse merkle tree nodes * @param left Input element array * @param right Input element array * @return Poseidon hash */ function _hashNode(uint256 left, uint256 right) internal view returns (uint256) { uint256[2] memory inputs; inputs[0] = left; inputs[1] = right; return _hash2Elements(inputs); } /** * @dev Hash poseidon for sparse merkle tree final nodes * @param key Input element array * @param value Input element array * @return Poseidon hash1 */ function _hashFinalNode(uint256 key, uint256 value) internal view returns (uint256) { uint256[3] memory inputs; inputs[0] = key; inputs[1] = value; inputs[2] = 1; return _hash3Elements(inputs); } /** * @dev Verify sparse merkle tree proof * @param root Root to verify * @param siblings Siblings necessary to compute the merkle proof * @param key Key to verify * @param value Value to verify * @return True if verification is correct, false otherwise */ function _smtVerifier( uint256 root, uint256[] memory siblings, uint256 key, uint256 value ) internal view returns (bool) { // Step 2: Calcuate root uint256 nextHash = _hashFinalNode(key, value); uint256 siblingTmp; for (int256 i = int256(siblings.length) - 1; i >= 0; i--) { siblingTmp = siblings[uint256(i)]; bool leftRight = (uint8(key >> i) & 0x01) == 1; nextHash = leftRight ? _hashNode(siblingTmp, nextHash) : _hashNode(nextHash, siblingTmp); } // Step 3: Check root return root == nextHash; } /** * @dev Build entry for the exit tree leaf * @param token Token identifier * @param nonce nonce parameter, only use 40 bits instead of 48 * @param balance Balance of the account * @param ay Public key babyjubjub represented as point: sign + (Ay) * @param ethAddress Ethereum address * @return uint256 array with the state variables */ function _buildTreeState( uint32 token, uint48 nonce, uint256 balance, uint256 ay, address ethAddress ) internal pure returns (uint256[4] memory) { uint256[4] memory stateArray; stateArray[0] = token; stateArray[0] |= nonce << 32; stateArray[0] |= (ay >> 255) << (32 + 40); // build element 2 stateArray[1] = balance; // build element 4 stateArray[2] = (ay << 1) >> 1; // last bit set to 0 // build element 5 stateArray[3] = uint256(ethAddress); return stateArray; } /** * @dev Decode half floating precision. * Max value encoded with this codification: 0x1f8def8800cca870c773f6eb4d980000000 (aprox 137 bits) * @param float Float half precision encode number * @return Decoded floating half precision */ function _float2Fix(uint40 float) internal pure returns (uint256) { uint256 m = float & 0x7FFFFFFFF; uint256 e = float >> 35; // never overflow, max "e" value is 32 uint256 exp = 10**e; // never overflow, max "fix" value is 1023 * 10^32 uint256 fix = m * exp; return fix; } /** * @dev Retrieve the DOMAIN_SEPARATOR hash * @return domainSeparator hash used for sign messages */ function DOMAIN_SEPARATOR() public view returns (bytes32 domainSeparator) { return keccak256( abi.encode( EIP712DOMAIN_HASH, NAME_HASH, VERSION_HASH, getChainId(), address(this) ) ); } /** * @return chainId The current chainId where the smarctoncract is executed */ function getChainId() public pure returns (uint256 chainId) { assembly { chainId := chainid() } } /** * @dev Retrieve ethereum address from a (defaultMessage + babyjub) signature * @param babyjub Public key babyjubjub represented as point: sign + (Ay) * @param r Signature parameter * @param s Signature parameter * @param v Signature parameter * @return Ethereum address recovered from the signature */ function _checkSig( bytes32 babyjub, bytes32 r, bytes32 s, uint8 v ) internal view returns (address) { // from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol#L46 // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "LitexHelpers::_checkSig: INVALID_S_VALUE" ); bytes32 encodeData = keccak256( abi.encode( AUTHORISE_TYPEHASH, LITEX_NETWORK_HASH, ACCOUNT_CREATION_HASH, babyjub ) ); bytes32 messageDigest = keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), encodeData) ); address ethAddress = ecrecover(messageDigest, v, r, s); require( ethAddress != address(0), "LitexHelpers::_checkSig: INVALID_SIGNATURE" ); return ethAddress; } /** * @dev return information from specific call data info * @param posParam parameter number relative to 0 to extract the info * @return ptr ptr to the call data position where the actual data starts * @return len Length of the data */ function _getCallData(uint256 posParam) internal pure returns (uint256 ptr, uint256 len) { assembly { let pos := add(4, mul(posParam, 32)) ptr := add(calldataload(pos), 4) len := calldataload(ptr) ptr := add(ptr, 32) } } /** * @dev This package fills at least len zeros in memory and a maximum of len+31 * @param ptr The position where it starts to fill zeros * @param len The minimum quantity of zeros it's added */ function _fillZeros(uint256 ptr, uint256 len) internal pure { assembly { let ptrTo := ptr ptr := add(ptr, len) for { } lt(ptrTo, ptr) { ptrTo := add(ptrTo, 32) } { mstore(ptrTo, 0) } } } /** * @dev Copy 'len' bytes from memory address 'src', to address 'dest'. * From https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol * @param _preBytes bytes storage * @param _postBytes Bytes array memory */ function _concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div( and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2 ) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } } interface IWithdrawalDelayer { /** * @notice Getter of the current `_litexGovernanceAddress` * @return The `_litexGovernanceAddress` value */ function getLitexGovernanceAddress() external view returns (address); /** * @dev Allows the current governance to set the pendingGovernance address. * @param newGovernance The address to transfer governance to. */ function transferGovernance(address newGovernance) external; /** * @dev Allows the pendingGovernance address to finalize the transfer. */ function claimGovernance() external; /** * @notice Getter of the current `_emergencyCouncil` * @return The `_emergencyCouncil` value */ function getEmergencyCouncil() external view returns (address); /** * @dev Allows the current governance to set the pendingGovernance address. * @param newEmergencyCouncil The address to transfer governance to. */ function transferEmergencyCouncil(address payable newEmergencyCouncil) external; /** * @dev Allows the pendingGovernance address to finalize the transfer. */ function claimEmergencyCouncil() external; /** * @notice Getter of the current `_emergencyMode` status to know if the emergency mode is enable or disable * @return The `_emergencyMode` value */ function isEmergencyMode() external view returns (bool); /** * @notice Getter to obtain the current withdrawal delay * @return the current withdrawal delay time in seconds: `_withdrawalDelay` */ function getWithdrawalDelay() external view returns (uint64); /** * @notice Getter to obtain when emergency mode started * @return the emergency mode starting time in seconds: `_emergencyModeStartingTime` */ function getEmergencyModeStartingTime() external view returns (uint64); /** * @notice This function enables the emergency mode. Only the keeper of the system can enable this mode. This cannot * be deactivated in any case so it will be irreversible. * @dev The activation time is saved in `_emergencyModeStartingTime` and this function can only be called * once if it has not been previously activated. * Events: `EmergencyModeEnabled` event. */ function enableEmergencyMode() external; /** * @notice This function allows the LitexKeeperAddress to change the withdrawal delay time, this is the time that * anyone needs to wait until a withdrawal of the funds is allowed. Since this time is calculated at the time of * withdrawal, this change affects existing deposits. Can never exceed `MAX_WITHDRAWAL_DELAY` * @dev It changes `_withdrawalDelay` if `_newWithdrawalDelay` it is less than or equal to MAX_WITHDRAWAL_DELAY * @param _newWithdrawalDelay new delay time in seconds * Events: `NewWithdrawalDelay` event. */ function changeWithdrawalDelay(uint64 _newWithdrawalDelay) external; /** * Returns the balance and the timestamp for a specific owner and token * @param _owner who can claim the deposit once the delay time has expired (if not in emergency mode) * @param _token address of the token to withdrawal (0x0 in case of Ether) * @return `amount` Total amount withdrawable (if not in emergency mode) * @return `depositTimestamp` Moment at which funds were deposited */ function depositInfo(address payable _owner, address _token) external view returns (uint192, uint64); /** * Function to make a deposit in the WithdrawalDelayer smartcontract, only the Litex rollup smartcontract can do it * @dev In case of an Ether deposit, the address `0x0` will be used and the corresponding amount must be sent in the * `msg.value`. In case of an ERC20 this smartcontract must have the approval to expend the token to * deposit to be able to make a transferFrom to itself. * @param _owner is who can claim the deposit once the withdrawal delay time has been exceeded * @param _token address of the token deposited (`0x0` in case of Ether) * @param _amount deposit amount * Events: `Deposit` */ function deposit( address _owner, address _token, uint192 _amount ) external payable; /** * This function allows the owner to withdawal the funds. Emergency mode cannot be enabled and it must have exceeded * the withdrawal delay time * @dev `NonReentrant` modifier is used as a protection despite the state is being previously updated * @param _owner can claim the deposit once the delay time has expired * @param _token address of the token to withdrawal (0x0 in case of Ether) * Events: `Withdraw` */ function withdrawal(address payable _owner, address _token) external; /** * Allows the Litex Governance to withdawal the funds in the event that emergency mode was enable. * Note: An Aragon Court will have the right to veto over the call to this method * @dev `NonReentrant` modifier is used as a protection despite the state is being previously updated and this is * a security mechanism * @param _to where the funds will be sent * @param _token address of the token withdraw (0x0 in case of Ether) * @param _amount the amount to send * Events: `EscapeHatchWithdrawal` */ function escapeHatchWithdrawal( address _to, address _token, uint256 _amount ) external; } contract InstantWithdrawManager is LitexHelpers { using SafeMath for uint256; // Number of buckets uint256 private constant _MAX_BUCKETS = 5; // Bucket array uint256 public nBuckets; mapping (int256 => uint256) public buckets; // Governance address address public litexGovernanceAddress; // Withdraw delay in seconds uint64 public withdrawalDelay; // ERC20 decimals signature // bytes4(keccak256(bytes("decimals()"))) bytes4 private constant _ERC20_DECIMALS = 0x313ce567; uint256 private constant _MAX_WITHDRAWAL_DELAY = 2 weeks; // Withdraw delayer interface IWithdrawalDelayer public withdrawDelayerContract; // Mapping tokenAddress --> (USD value)/token , default 0, means that token does not worth // 2^64 = 1.8446744e+19 // fixed point codification is used, 9 digits for integer part, 10 digits for decimal // In other words, the USD value of a token base unit is multiplied by 1e10 // MaxUSD value for a base unit token: 1844674407,3709551616$ // MinUSD value for a base unit token: 1e-10$ mapping(address => uint64) public tokenExchange; uint256 private constant _EXCHANGE_MULTIPLIER = 1e10; event UpdateBucketWithdraw( uint8 indexed numBucket, uint256 indexed blockStamp, uint256 withdrawals ); event UpdateWithdrawalDelay(uint64 newWithdrawalDelay); event UpdateBucketsParameters(uint256[] arrayBuckets); event UpdateTokenExchange(address[] addressArray, uint64[] valueArray); event SafeMode(); function _initializeWithdraw( address _litexGovernanceAddress, uint64 _withdrawalDelay, address _withdrawDelayerContract ) internal initializer { litexGovernanceAddress = _litexGovernanceAddress; withdrawalDelay = _withdrawalDelay; withdrawDelayerContract = IWithdrawalDelayer(_withdrawDelayerContract); } modifier onlyGovernance { require( msg.sender == litexGovernanceAddress, "InstantWithdrawManager::onlyGovernance: ONLY_GOVERNANCE_ADDRESS" ); _; } /** * @dev Attempt to use instant withdraw * @param tokenAddress Token address * @param amount Amount to withdraw */ function _processInstantWithdrawal(address tokenAddress, uint192 amount) internal returns (bool) { // find amount in USD and then the corresponding bucketIdx uint256 amountUSD = _token2USD(tokenAddress, amount); if (amountUSD == 0) { return true; } // find the appropiate bucketId int256 bucketIdx = _findBucketIdx(amountUSD); if (bucketIdx == -1) return true; (uint256 ceilUSD, uint256 blockStamp, uint256 withdrawals, uint256 rateBlocks, uint256 rateWithdrawals, uint256 maxWithdrawals) = unpackBucket(buckets[bucketIdx]); // update the bucket and check again if are withdrawals available uint256 differenceBlocks = block.number.sub(blockStamp); uint256 periods = differenceBlocks.div(rateBlocks); // add the withdrawals available withdrawals = withdrawals.add(periods.mul(rateWithdrawals)); if (withdrawals >= maxWithdrawals) { withdrawals = maxWithdrawals; blockStamp = block.number; } else { blockStamp = blockStamp.add(periods.mul(rateBlocks)); } if (withdrawals == 0) return false; withdrawals = withdrawals.sub(1); // update the bucket with the new values buckets[bucketIdx] = packBucket(ceilUSD, blockStamp, withdrawals, rateBlocks, rateWithdrawals, maxWithdrawals); emit UpdateBucketWithdraw(uint8(bucketIdx), blockStamp, withdrawals); return true; } /** * @dev Update bucket parameters * @param newBuckets Array of buckets to replace the current ones, this array includes the * following parameters: [ceilUSD, withdrawals, rateBlocks, rateWithdrawals, maxWithdrawals] */ function updateBucketsParameters( uint256[] memory newBuckets ) external onlyGovernance { uint256 n = newBuckets.length; require( n <= _MAX_BUCKETS, "InstantWithdrawManager::updateBucketsParameters: MAX_NUM_BUCKETS" ); nBuckets = n; for (uint256 i = 0; i < n; i++) { (uint256 ceilUSD, , uint256 withdrawals, uint256 rateBlocks, uint256 rateWithdrawals, uint256 maxWithdrawals) = unpackBucket(newBuckets[i]); require( withdrawals <= maxWithdrawals, "InstantWithdrawManager::updateBucketsParameters: WITHDRAWALS_MUST_BE_LESS_THAN_MAXWITHDRAWALS" ); require( rateBlocks > 0, "InstantWithdrawManager::updateBucketsParameters: RATE_BLOCKS_MUST_BE_MORE_THAN_0" ); buckets[int256(i)] = packBucket( ceilUSD, block.number, withdrawals, rateBlocks, rateWithdrawals, maxWithdrawals ); } emit UpdateBucketsParameters(newBuckets); } /** * @dev Update token USD value * @param addressArray Array of the token address * @param valueArray Array of USD values */ function updateTokenExchange( address[] memory addressArray, uint64[] memory valueArray ) external onlyGovernance { require( addressArray.length == valueArray.length, "InstantWithdrawManager::updateTokenExchange: INVALID_ARRAY_LENGTH" ); for (uint256 i = 0; i < addressArray.length; i++) { tokenExchange[addressArray[i]] = valueArray[i]; } emit UpdateTokenExchange(addressArray, valueArray); } /** * @dev Update WithdrawalDelay * @param newWithdrawalDelay New WithdrawalDelay * Events: `UpdateWithdrawalDelay` */ function updateWithdrawalDelay(uint64 newWithdrawalDelay) external onlyGovernance { require( newWithdrawalDelay <= _MAX_WITHDRAWAL_DELAY, "InstantWithdrawManager::updateWithdrawalDelay: EXCEED_MAX_WITHDRAWAL_DELAY" ); withdrawalDelay = newWithdrawalDelay; emit UpdateWithdrawalDelay(newWithdrawalDelay); } /** * @dev Put the smartcontract in safe mode, only delayed withdrawals allowed, * also update the 'withdrawalDelay' of the 'withdrawDelayer' contract */ function safeMode() external onlyGovernance { // only 1 bucket that does not allow any instant withdraw nBuckets = 1; buckets[0] = packBucket( 0xFFFFFFFF_FFFFFFFF_FFFFFFFF, 0, 0, 1, 0, 0 ); withdrawDelayerContract.changeWithdrawalDelay(withdrawalDelay); emit SafeMode(); } /** * @dev Return true if a instant withdraw could be done with that 'tokenAddress' and 'amount' * @param tokenAddress Token address * @param amount Amount to withdraw * @return true if the instant withdrawal is allowed */ function instantWithdrawalViewer(address tokenAddress, uint192 amount) public view returns (bool) { // find amount in USD and then the corresponding bucketIdx uint256 amountUSD = _token2USD(tokenAddress, amount); if (amountUSD == 0) return true; int256 bucketIdx = _findBucketIdx(amountUSD); if (bucketIdx == -1) return true; (, uint256 blockStamp, uint256 withdrawals, uint256 rateBlocks, uint256 rateWithdrawals, uint256 maxWithdrawals) = unpackBucket(buckets[bucketIdx]); uint256 differenceBlocks = block.number.sub(blockStamp); uint256 periods = differenceBlocks.div(rateBlocks); withdrawals = withdrawals.add(periods.mul(rateWithdrawals)); if (withdrawals>maxWithdrawals) withdrawals = maxWithdrawals; if (withdrawals == 0) return false; return true; } /** * @dev Converts tokens to USD * @param tokenAddress Token address * @param amount Token amount * @return Total USD amount */ function _token2USD(address tokenAddress, uint192 amount) internal view returns (uint256) { if (tokenExchange[tokenAddress] == 0) return 0; // this multiplication never overflows 192bits * 64 bits uint256 baseUnitTokenUSD = (uint256(amount) * uint256(tokenExchange[tokenAddress])) / _EXCHANGE_MULTIPLIER; uint8 decimals; // in case of ether, set 18 decimals if (tokenAddress == address(0)) { decimals = 18; } else { // if decimals() is not implemented 0 decimals are assumed (bool success, bytes memory data) = tokenAddress.staticcall( abi.encodeWithSelector(_ERC20_DECIMALS) ); if (success) { decimals = abi.decode(data, (uint8)); } } require( decimals < 77, "InstantWithdrawManager::_token2USD: TOKEN_DECIMALS_OVERFLOW" ); return baseUnitTokenUSD / (10**uint256(decimals)); } /** * @dev Find the corresponding bucket for the input amount * @param amountUSD USD amount * @return Bucket index, -1 in case there is no match */ function _findBucketIdx(uint256 amountUSD) internal view returns (int256) { for (int256 i = 0; i < int256(nBuckets); i++) { uint256 ceilUSD = buckets[i] & 0xFFFFFFFF_FFFFFFFF_FFFFFFFF; if ((amountUSD <= ceilUSD) || (ceilUSD == 0xFFFFFFFF_FFFFFFFF_FFFFFFFF)) { return i; } } return -1; } /** * @dev Unpack a packed uint256 into the bucket parameters * @param bucket Token address * @return ceilUSD max USD value that bucket holds * @return blockStamp block number of the last bucket update * @return withdrawals available withdrawals of the bucket * @return rateBlocks every `rateBlocks` blocks add `rateWithdrawals` withdrawal * @return rateWithdrawals add `rateWithdrawals` every `rateBlocks` * @return maxWithdrawals max withdrawals the bucket can hold */ function unpackBucket(uint256 bucket) public pure returns( uint256 ceilUSD, uint256 blockStamp, uint256 withdrawals, uint256 rateBlocks, uint256 rateWithdrawals, uint256 maxWithdrawals ) { ceilUSD = bucket & 0xFFFFFFFF_FFFFFFFF_FFFFFFFF; blockStamp = (bucket >> 96) & 0xFFFFFFFF; withdrawals = (bucket >> 128) & 0xFFFFFFFF; rateBlocks = (bucket >> 160) & 0xFFFFFFFF; rateWithdrawals = (bucket >> 192) & 0xFFFFFFFF; maxWithdrawals = (bucket >> 224) & 0xFFFFFFFF; } /** * @dev Pack all the bucket parameters into a uint256 * @param ceilUSD max USD value that bucket holds * @param blockStamp block number of the last bucket update * @param withdrawals available withdrawals of the bucket * @param rateBlocks every `rateBlocks` blocks add `rateWithdrawals` withdrawal * @param rateWithdrawals add `rateWithdrawals` every `rateBlocks` * @param maxWithdrawals max withdrawals the bucket can hold * @return ret all bucket varaibles packed [ceilUSD, blockStamp, withdrawals, rateBlocks, rateWithdrawals, maxWithdrawals] */ function packBucket( uint256 ceilUSD, uint256 blockStamp, uint256 withdrawals, uint256 rateBlocks, uint256 rateWithdrawals, uint256 maxWithdrawals ) public pure returns(uint256 ret) { ret = ceilUSD | (blockStamp << 96) | (withdrawals << 128) | (rateBlocks << 160) | (rateWithdrawals << 192) | (maxWithdrawals << 224); } } /** * @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); } contract LitexRollup is InstantWithdrawManager { struct VerifierRollup { VerifierRollupInterface verifierInterface; uint256 maxTx; // maximum rollup transactions in a batch: L2-tx + L1-tx transactions uint256 nLevels; // number of levels of the circuit } // ERC20 signatures: // bytes4(keccak256(bytes("transfer(address,uint256)"))); bytes4 constant _TRANSFER_SIGNATURE = 0xa9059cbb; // bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); bytes4 constant _TRANSFER_FROM_SIGNATURE = 0x23b872dd; // bytes4(keccak256(bytes("approve(address,uint256)"))); bytes4 constant _APPROVE_SIGNATURE = 0x095ea7b3; // ERC20 extensions: // bytes4(keccak256(bytes("permit(address,address,uint256,uint256,uint8,bytes32,bytes32)"))); bytes4 constant _PERMIT_SIGNATURE = 0xd505accf; // First 256 indexes reserved, first user index will be the 256 uint48 constant _RESERVED_IDX = 255; // IDX 1 is reserved for exits uint48 constant _EXIT_IDX = 1; // Max load amount allowed (loadAmount: L1 --> L2) uint256 constant _LIMIT_LOAD_AMOUNT = (1 << 128); // Max amount allowed (amount L2 --> L2) uint256 constant _LIMIT_L2TRANSFER_AMOUNT = (1 << 192); // Max number of tokens allowed to be registered inside the rollup uint256 constant _LIMIT_TOKENS = (1 << 32); // [65 bytes] compressedSignature + [32 bytes] fromBjj-compressed + [4 bytes] tokenId uint256 constant _L1_COORDINATOR_TOTALBYTES = 101; // [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6 bytes] fromIdx + // [5 bytes] loadAmountFloat40 + [5 bytes] amountFloat40 + [4 bytes] tokenId + [6 bytes] toIdx uint256 constant _L1_USER_TOTALBYTES = 78; // User TXs are the TX made by the user with a L1 TX // Coordinator TXs are the L2 account creation made by the coordinator whose signature // needs to be verified in L1. // The maximum number of L1-user TXs and L1-coordinartor-TX is limited by the _MAX_L1_TX // And the maximum User TX is _MAX_L1_USER_TX // Maximum L1-user transactions allowed to be queued in a batch uint256 constant _MAX_L1_USER_TX = 128; // Maximum L1 transactions allowed to be queued in a batch uint256 constant _MAX_L1_TX = 256; // Modulus zkSNARK uint256 constant _RFIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; // [6 bytes] lastIdx + [6 bytes] newLastIdx + [32 bytes] stateRoot + [32 bytes] newStRoot + [32 bytes] newExitRoot + // [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + totall1L2TxsDataLength + feeIdxCoordinatorLength + [2 bytes] chainID + [4 bytes] batchNum = // 18546 bytes + totall1L2TxsDataLength + feeIdxCoordinatorLength uint256 constant _INPUT_SHA_CONSTANT_BYTES = 20082; uint8 public constant ABSOLUTE_MAX_L1L2BATCHTIMEOUT = 240; // This ethereum address is used internally for rollup accounts that don't have ethereum address, only Babyjubjub // This non-ethereum accounts can be created by the coordinator and allow users to have a rollup // account without needing an ethereum address address constant _ETH_ADDRESS_INTERNAL_ONLY = address( 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF ); // Verifiers array VerifierRollup[] public rollupVerifiers; // Withdraw verifier interface VerifierWithdrawInterface public withdrawVerifier; // Last account index created inside the rollup uint48 public lastIdx; // Last batch forged uint32 public lastForgedBatch; // Each batch forged will have a correlated 'state root' mapping(uint32 => uint256) public stateRootMap; // Each batch forged will have a correlated 'exit tree' represented by the exit root mapping(uint32 => uint256) public exitRootsMap; // Each batch forged will have a correlated 'l1L2TxDataHash' mapping(uint32 => bytes32) public l1L2TxsDataHashMap; // Mapping of exit nullifiers, only allowing each withdrawal to be made once // rootId => (Idx => true/false) mapping(uint32 => mapping(uint48 => bool)) public exitNullifierMap; // List of ERC20 tokens that can be used in rollup // ID = 0 will be reserved for ether address[] public tokenList; // Mapping addres of the token, with the tokenID associated mapping(address => uint256) public tokenMap; // Fee for adding a new token to the rollup in LXT tokens uint256 public feeAddToken; // Contract interface of the litex auction ILitexAuctionProtocol public litexAuctionContract; // Map of queues of L1-user-tx transactions, the transactions are stored in bytes32 sequentially // The coordinator is forced to forge the next queue in the next L1-L2-batch mapping(uint32 => bytes) public mapL1TxQueue; // Ethereum block where the last L1-L2-batch was forged uint64 public lastL1L2Batch; // Queue index that will be forged in the next L1-L2-batch uint32 public nextL1ToForgeQueue; // Queue index wich will be filled with the following L1-User-Tx uint32 public nextL1FillingQueue; // Max ethereum blocks after the last L1-L2-batch, when exceeds the timeout only L1-L2-batch are allowed uint8 public forgeL1L2BatchTimeout; // LXT token address address public tokenLXT; // Event emitted when a L1-user transaction is called and added to the nextL1FillingQueue queue event L1UserTxEvent( uint32 indexed queueIndex, uint8 indexed position, // Position inside the queue where the TX resides bytes l1UserTx ); // Event emitted when a new token is added event AddToken(address indexed tokenAddress, uint32 tokenID); // Event emitted every time a batch is forged event ForgeBatch(uint32 indexed batchNum, uint16 l1UserTxsLen); // Event emitted when the governance update the `forgeL1L2BatchTimeout` event UpdateForgeL1L2BatchTimeout(uint8 newForgeL1L2BatchTimeout); // Event emitted when the governance update the `feeAddToken` event UpdateFeeAddToken(uint256 newFeeAddToken); // Event emitted when a withdrawal is done event WithdrawEvent( uint48 indexed idx, uint32 indexed numExitRoot, bool indexed instantWithdraw ); // Event emitted when the contract is initialized event InitializeLitexEvent( uint8 forgeL1L2BatchTimeout, uint256 feeAddToken, uint64 withdrawalDelay ); // Event emitted when the contract is updated to the new version event litexV2(); function updateVerifiers() external { require( msg.sender == address(0xb6D3f1056c015962fA66A4020E50522B58292D1E), "Litex::updateVerifiers ONLY_DEPLOYER" ); require( rollupVerifiers[0].maxTx == 344, // Old verifier 344 tx "Litex::updateVerifiers VERIFIERS_ALREADY_UPDATED" ); rollupVerifiers[0] = VerifierRollup({ verifierInterface: VerifierRollupInterface( address(0x3DAa0B2a994b1BC60dB9e312aD0a8d87a1Bb16D2) // New verifier 400 tx ), maxTx: 400, nLevels: 32 }); rollupVerifiers[1] = VerifierRollup({ verifierInterface: VerifierRollupInterface( address(0x1DC4b451DFcD0e848881eDE8c7A99978F00b1342) // New verifier 2048 tx ), maxTx: 2048, nLevels: 32 }); withdrawVerifier = VerifierWithdrawInterface( 0x4464A1E499cf5443541da6728871af1D5C4920ca ); emit litexV2(); } /** * @dev Initializer function (equivalent to the constructor). Since we use * upgradeable smartcontracts the state vars have to be initialized here. */ function initializeLitex( address[] memory _verifiers, uint256[] memory _verifiersParams, address _withdrawVerifier, address _litexAuctionContract, address _tokenLXT, uint8 _forgeL1L2BatchTimeout, uint256 _feeAddToken, address _poseidon2Elements, address _poseidon3Elements, address _poseidon4Elements, address _litexGovernanceAddress, uint64 _withdrawalDelay, address _withdrawDelayerContract ) external initializer { require( _litexAuctionContract != address(0) && _withdrawDelayerContract != address(0), "Litex::initializeLitex ADDRESS_0_NOT_VALID" ); // set state variables _initializeVerifiers(_verifiers, _verifiersParams); withdrawVerifier = VerifierWithdrawInterface(_withdrawVerifier); litexAuctionContract = ILitexAuctionProtocol(_litexAuctionContract); tokenLXT = _tokenLXT; forgeL1L2BatchTimeout = _forgeL1L2BatchTimeout; feeAddToken = _feeAddToken; // set default state variables lastIdx = _RESERVED_IDX; // lastL1L2Batch = 0 --> first batch forced to be L1Batch // nextL1ToForgeQueue = 0 --> First queue will be forged nextL1FillingQueue = 1; // stateRootMap[0] = 0 --> genesis batch will have root = 0 tokenList.push(address(0)); // Token 0 is ETH // initialize libs _initializeHelpers( _poseidon2Elements, _poseidon3Elements, _poseidon4Elements ); _initializeWithdraw( _litexGovernanceAddress, _withdrawalDelay, _withdrawDelayerContract ); emit InitializeLitexEvent( _forgeL1L2BatchTimeout, _feeAddToken, _withdrawalDelay ); } ////////////// // Coordinator operations ///////////// /** * @dev Forge a new batch providing the L2 Transactions, L1Corrdinator transactions and the proof. * If the proof is succesfully verified, update the current state, adding a new state and exit root. * In order to optimize the gas consumption the parameters `encodedL1CoordinatorTx`, `l1L2TxsData` and `feeIdxCoordinator` * are read directly from the calldata using assembly with the instruction `calldatacopy` * @param newLastIdx New total rollup accounts * @param newStRoot New state root * @param newExitRoot New exit root * @param encodedL1CoordinatorTx Encoded L1-coordinator transactions * @param l1L2TxsData Encoded l2 data * @param feeIdxCoordinator Encoded idx accounts of the coordinator where the fees will be payed * @param verifierIdx Verifier index * @param l1Batch Indicates if this batch will be L2 or L1-L2 * @param proofA zk-snark input * @param proofB zk-snark input * @param proofC zk-snark input * Events: `ForgeBatch` */ function forgeBatch( uint48 newLastIdx, uint256 newStRoot, uint256 newExitRoot, bytes calldata encodedL1CoordinatorTx, bytes calldata l1L2TxsData, bytes calldata feeIdxCoordinator, uint8 verifierIdx, bool l1Batch, uint256[2] calldata proofA, uint256[2][2] calldata proofB, uint256[2] calldata proofC ) external virtual { // Assure data availability from regular ethereum nodes // We include this line because it's easier to track the transaction data, as it will never be in an internal TX. // In general this makes no sense, as callling this function from another smart contract will have to pay the calldata twice. // But forcing, it avoids having to check. require( msg.sender == tx.origin, "Litex::forgeBatch: INTENAL_TX_NOT_ALLOWED" ); // ask the auction if this coordinator is allow to forge require( litexAuctionContract.canForge(msg.sender, block.number) == true, "Litex::forgeBatch: AUCTION_DENIED" ); if (!l1Batch) { require( block.number < (lastL1L2Batch + forgeL1L2BatchTimeout), // No overflow since forgeL1L2BatchTimeout is an uint8 "Litex::forgeBatch: L1L2BATCH_REQUIRED" ); } // calculate input uint256 input = _constructCircuitInput( newLastIdx, newStRoot, newExitRoot, l1Batch, verifierIdx ); // verify proof require( rollupVerifiers[verifierIdx].verifierInterface.verifyProof( proofA, proofB, proofC, [input] ), "Litex::forgeBatch: INVALID_PROOF" ); // update state lastForgedBatch++; lastIdx = newLastIdx; stateRootMap[lastForgedBatch] = newStRoot; exitRootsMap[lastForgedBatch] = newExitRoot; l1L2TxsDataHashMap[lastForgedBatch] = sha256(l1L2TxsData); uint16 l1UserTxsLen; if (l1Batch) { // restart the timeout lastL1L2Batch = uint64(block.number); // clear current queue l1UserTxsLen = _clearQueue(); } // auction must be aware that a batch is being forged litexAuctionContract.forge(msg.sender); emit ForgeBatch(lastForgedBatch, l1UserTxsLen); } ////////////// // User L1 rollup tx ///////////// // This are all the possible L1-User transactions: // | fromIdx | toIdx | loadAmountF | amountF | tokenID(SC) | babyPubKey | l1-user-TX | // |:-------:|:-----:|:-----------:|:-------:|:-----------:|:----------:|:-------------------------------:| // | 0 | 0 | 0 | 0(SC) | X | !=0(SC) | createAccount | // | 0 | 0 | !=0 | 0(SC) | X | !=0(SC) | createAccountDeposit | // | 0 | 255+ | X | X | X | !=0(SC) | createAccountDepositAndTransfer | // | 255+ | 0 | X | 0(SC) | X | 0(SC) | Deposit | // | 255+ | 1 | 0 | X | X | 0(SC) | Exit | // | 255+ | 255+ | 0 | X | X | 0(SC) | Transfer | // | 255+ | 255+ | !=0 | X | X | 0(SC) | DepositAndTransfer | // As can be seen in the table the type of transaction is determined basically by the "fromIdx" and "toIdx" // The 'X' means that can be any valid value and does not change the l1-user-tx type // Other parameters must be consistent, for example, if toIdx is 0, amountF must be 0, because there's no L2 transfer /** * @dev Create a new rollup l1 user transaction * @param babyPubKey Public key babyjubjub represented as point: sign + (Ay) * @param fromIdx Index leaf of sender account or 0 if create new account * @param loadAmountF Amount from L1 to L2 to sender account or new account * @param amountF Amount transfered between L2 accounts * @param tokenID Token identifier * @param toIdx Index leaf of recipient account, or _EXIT_IDX if exit, or 0 if not transfer * Events: `L1UserTxEvent` */ function addL1Transaction( uint256 babyPubKey, uint48 fromIdx, uint40 loadAmountF, uint40 amountF, uint32 tokenID, uint48 toIdx, bytes calldata permit ) external payable { // check tokenID require( tokenID < tokenList.length, "Litex::addL1Transaction: TOKEN_NOT_REGISTERED" ); // check loadAmount uint256 loadAmount = _float2Fix(loadAmountF); require( loadAmount < _LIMIT_LOAD_AMOUNT, "Litex::addL1Transaction: LOADAMOUNT_EXCEED_LIMIT" ); // deposit token or ether if (loadAmount > 0) { if (tokenID == 0) { require( loadAmount == msg.value, "Litex::addL1Transaction: LOADAMOUNT_ETH_DOES_NOT_MATCH" ); } else { require( msg.value == 0, "Litex::addL1Transaction: MSG_VALUE_NOT_EQUAL_0" ); if (permit.length != 0) { _permit(tokenList[tokenID], loadAmount, permit); } uint256 prevBalance = IERC20(tokenList[tokenID]).balanceOf( address(this) ); _safeTransferFrom( tokenList[tokenID], msg.sender, address(this), loadAmount ); uint256 postBalance = IERC20(tokenList[tokenID]).balanceOf( address(this) ); require( postBalance - prevBalance == loadAmount, "Litex::addL1Transaction: LOADAMOUNT_ERC20_DOES_NOT_MATCH" ); } } // perform L1 User Tx _addL1Transaction( msg.sender, babyPubKey, fromIdx, loadAmountF, amountF, tokenID, toIdx ); } /** * @dev Create a new rollup l1 user transaction * @param ethAddress Ethereum addres of the sender account or new account * @param babyPubKey Public key babyjubjub represented as point: sign + (Ay) * @param fromIdx Index leaf of sender account or 0 if create new account * @param loadAmountF Amount from L1 to L2 to sender account or new account * @param amountF Amount transfered between L2 accounts * @param tokenID Token identifier * @param toIdx Index leaf of recipient account, or _EXIT_IDX if exit, or 0 if not transfer * Events: `L1UserTxEvent` */ function _addL1Transaction( address ethAddress, uint256 babyPubKey, uint48 fromIdx, uint40 loadAmountF, uint40 amountF, uint32 tokenID, uint48 toIdx ) internal { uint256 amount = _float2Fix(amountF); require( amount < _LIMIT_L2TRANSFER_AMOUNT, "Litex::_addL1Transaction: AMOUNT_EXCEED_LIMIT" ); // toIdx can be: 0, _EXIT_IDX or (toIdx > _RESERVED_IDX) if (toIdx == 0) { require( (amount == 0), "Litex::_addL1Transaction: AMOUNT_MUST_BE_0_IF_NOT_TRANSFER" ); } else { if ((toIdx == _EXIT_IDX)) { require( (loadAmountF == 0), "Litex::_addL1Transaction: LOADAMOUNT_MUST_BE_0_IF_EXIT" ); } else { require( ((toIdx > _RESERVED_IDX) && (toIdx <= lastIdx)), "Litex::_addL1Transaction: INVALID_TOIDX" ); } } // fromIdx can be: 0 if create account or (fromIdx > _RESERVED_IDX) if (fromIdx == 0) { require( babyPubKey != 0, "Litex::_addL1Transaction: INVALID_CREATE_ACCOUNT_WITH_NO_BABYJUB" ); } else { require( (fromIdx > _RESERVED_IDX) && (fromIdx <= lastIdx), "Litex::_addL1Transaction: INVALID_FROMIDX" ); require( babyPubKey == 0, "Litex::_addL1Transaction: BABYJUB_MUST_BE_0_IF_NOT_CREATE_ACCOUNT" ); } _l1QueueAddTx( ethAddress, babyPubKey, fromIdx, loadAmountF, amountF, tokenID, toIdx ); } ////////////// // User operations ///////////// /** * @dev Withdraw to retrieve the tokens from the exit tree to the owner account * Before this call an exit transaction must be done * @param tokenID Token identifier * @param amount Amount to retrieve * @param babyPubKey Public key babyjubjub represented as point: sign + (Ay) * @param numExitRoot Batch number where the exit transaction has been done * @param siblings Siblings to demonstrate merkle tree proof * @param idx Index of the exit tree account * @param instantWithdraw true if is an instant withdraw * Events: `WithdrawEvent` */ function withdrawMerkleProof( uint32 tokenID, uint192 amount, uint256 babyPubKey, uint32 numExitRoot, uint256[] memory siblings, uint48 idx, bool instantWithdraw ) external { // numExitRoot is not checked because an invalid numExitRoot will bring to a 0 root // and this is an empty tree. // in case of instant withdraw assure that is available if (instantWithdraw) { require( _processInstantWithdrawal(tokenList[tokenID], amount), "Litex::withdrawMerkleProof: INSTANT_WITHDRAW_WASTED_FOR_THIS_USD_RANGE" ); } // build 'key' and 'value' for exit tree uint256[4] memory arrayState = _buildTreeState( tokenID, 0, amount, babyPubKey, msg.sender ); uint256 stateHash = _hash4Elements(arrayState); // get exit root given its index depth uint256 exitRoot = exitRootsMap[numExitRoot]; // check exit tree nullifier require( exitNullifierMap[numExitRoot][idx] == false, "Litex::withdrawMerkleProof: WITHDRAW_ALREADY_DONE" ); // check sparse merkle tree proof require( _smtVerifier(exitRoot, siblings, idx, stateHash) == true, "Litex::withdrawMerkleProof: SMT_PROOF_INVALID" ); // set nullifier exitNullifierMap[numExitRoot][idx] = true; _withdrawFunds(amount, tokenID, instantWithdraw); emit WithdrawEvent(idx, numExitRoot, instantWithdraw); } /** * @dev Withdraw to retrieve the tokens from the exit tree to the owner account * Before this call an exit transaction must be done * @param proofA zk-snark input * @param proofB zk-snark input * @param proofC zk-snark input * @param tokenID Token identifier * @param amount Amount to retrieve * @param numExitRoot Batch number where the exit transaction has been done * @param idx Index of the exit tree account * @param instantWithdraw true if is an instant withdraw * Events: `WithdrawEvent` */ function withdrawCircuit( uint256[2] calldata proofA, uint256[2][2] calldata proofB, uint256[2] calldata proofC, uint32 tokenID, uint192 amount, uint32 numExitRoot, uint48 idx, bool instantWithdraw ) external { // in case of instant withdraw assure that is available if (instantWithdraw) { require( _processInstantWithdrawal(tokenList[tokenID], amount), "Litex::withdrawCircuit: INSTANT_WITHDRAW_WASTED_FOR_THIS_USD_RANGE" ); } require( exitNullifierMap[numExitRoot][idx] == false, "Litex::withdrawCircuit: WITHDRAW_ALREADY_DONE" ); // get exit root given its index depth uint256 exitRoot = exitRootsMap[numExitRoot]; uint256 input = uint256( sha256(abi.encodePacked(exitRoot, msg.sender, tokenID, amount, idx)) ) % _RFIELD; // verify zk-snark circuit require( withdrawVerifier.verifyProof(proofA, proofB, proofC, [input]) == true, "Litex::withdrawCircuit: INVALID_ZK_PROOF" ); // set nullifier exitNullifierMap[numExitRoot][idx] = true; _withdrawFunds(amount, tokenID, instantWithdraw); emit WithdrawEvent(idx, numExitRoot, instantWithdraw); } ////////////// // Governance methods ///////////// /** * @dev Update ForgeL1L2BatchTimeout * @param newForgeL1L2BatchTimeout New ForgeL1L2BatchTimeout * Events: `UpdateForgeL1L2BatchTimeout` */ function updateForgeL1L2BatchTimeout(uint8 newForgeL1L2BatchTimeout) external onlyGovernance { require( newForgeL1L2BatchTimeout <= ABSOLUTE_MAX_L1L2BATCHTIMEOUT, "Litex::updateForgeL1L2BatchTimeout: MAX_FORGETIMEOUT_EXCEED" ); forgeL1L2BatchTimeout = newForgeL1L2BatchTimeout; emit UpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout); } /** * @dev Update feeAddToken * @param newFeeAddToken New feeAddToken * Events: `UpdateFeeAddToken` */ function updateFeeAddToken(uint256 newFeeAddToken) external onlyGovernance { feeAddToken = newFeeAddToken; emit UpdateFeeAddToken(newFeeAddToken); } ////////////// // Viewers ///////////// /** * @dev Retrieve the number of tokens added in rollup * @return Number of tokens added in rollup */ function registerTokensCount() public view returns (uint256) { return tokenList.length; } /** * @dev Retrieve the number of rollup verifiers * @return Number of verifiers */ function rollupVerifiersLength() public view returns (uint256) { return rollupVerifiers.length; } ////////////// // Internal/private methods ///////////// /** * @dev Inclusion of a new token to the rollup * @param tokenAddress Smart contract token address * Events: `AddToken` */ function addToken(address tokenAddress, bytes calldata permit) public { require( IERC20(tokenAddress).totalSupply() > 0, "Litex::addToken: TOTAL_SUPPLY_ZERO" ); uint256 currentTokens = tokenList.length; require( currentTokens < _LIMIT_TOKENS, "Litex::addToken: TOKEN_LIST_FULL" ); require( tokenAddress != address(0), "Litex::addToken: ADDRESS_0_INVALID" ); require(tokenMap[tokenAddress] == 0, "Litex::addToken: ALREADY_ADDED"); if (msg.sender != litexGovernanceAddress) { // permit and transfer LXT tokens if (permit.length != 0) { _permit(tokenLXT, feeAddToken, permit); } _safeTransferFrom( tokenLXT, msg.sender, litexGovernanceAddress, feeAddToken ); } tokenList.push(tokenAddress); tokenMap[tokenAddress] = currentTokens; emit AddToken(tokenAddress, uint32(currentTokens)); } /** * @dev Initialize verifiers * @param _verifiers verifiers address array * @param _verifiersParams encoeded maxTx and nlevels of the verifier as follows: * [8 bits]nLevels || [248 bits] maxTx */ function _initializeVerifiers( address[] memory _verifiers, uint256[] memory _verifiersParams ) internal { for (uint256 i = 0; i < _verifiers.length; i++) { rollupVerifiers.push( VerifierRollup({ verifierInterface: VerifierRollupInterface(_verifiers[i]), maxTx: (_verifiersParams[i] << 8) >> 8, nLevels: _verifiersParams[i] >> (256 - 8) }) ); } } /** * @dev Add L1-user-tx, add it to the correspoding queue * l1Tx L1-user-tx encoded in bytes as follows: [20 bytes] fromEthAddr || [32 bytes] fromBjj-compressed || [4 bytes] fromIdx || * [5 bytes] loadAmountFloat40 || [5 bytes] amountFloat40 || [4 bytes] tokenId || [4 bytes] toIdx * @param ethAddress Ethereum address of the rollup account * @param babyPubKey Public key babyjubjub represented as point: sign + (Ay) * @param fromIdx Index account of the sender account * @param loadAmountF Amount from L1 to L2 * @param amountF Amount transfered between L2 accounts * @param tokenID Token identifier * @param toIdx Index leaf of recipient account * Events: `L1UserTxEvent` */ function _l1QueueAddTx( address ethAddress, uint256 babyPubKey, uint48 fromIdx, uint40 loadAmountF, uint40 amountF, uint32 tokenID, uint48 toIdx ) internal { bytes memory l1Tx = abi.encodePacked( ethAddress, babyPubKey, fromIdx, loadAmountF, amountF, tokenID, toIdx ); uint256 currentPosition = mapL1TxQueue[nextL1FillingQueue].length / _L1_USER_TOTALBYTES; // concatenate storage byte array with the new l1Tx _concatStorage(mapL1TxQueue[nextL1FillingQueue], l1Tx); emit L1UserTxEvent(nextL1FillingQueue, uint8(currentPosition), l1Tx); if (currentPosition + 1 >= _MAX_L1_USER_TX) { nextL1FillingQueue++; } } /** * @dev return the current L1-user-tx queue adding the L1-coordinator-tx * @param ptr Ptr where L1 data is set * @param l1Batch if true, the include l1TXs from the queue * [1 byte] V(ecdsa signature) || [32 bytes] S(ecdsa signature) || * [32 bytes] R(ecdsa signature) || [32 bytes] fromBjj-compressed || [4 bytes] tokenId */ function _buildL1Data(uint256 ptr, bool l1Batch) internal view { uint256 dPtr; uint256 dLen; (dPtr, dLen) = _getCallData(3); uint256 l1CoordinatorLength = dLen / _L1_COORDINATOR_TOTALBYTES; uint256 l1UserLength; bytes memory l1UserTxQueue; if (l1Batch) { l1UserTxQueue = mapL1TxQueue[nextL1ToForgeQueue]; l1UserLength = l1UserTxQueue.length / _L1_USER_TOTALBYTES; } else { l1UserLength = 0; } require( l1UserLength + l1CoordinatorLength <= _MAX_L1_TX, "Litex::_buildL1Data: L1_TX_OVERFLOW" ); if (l1UserLength > 0) { // Copy the queue to the ptr and update ptr assembly { let ptrFrom := add(l1UserTxQueue, 0x20) let ptrTo := ptr ptr := add(ptr, mul(l1UserLength, _L1_USER_TOTALBYTES)) for { } lt(ptrTo, ptr) { ptrTo := add(ptrTo, 32) ptrFrom := add(ptrFrom, 32) } { mstore(ptrTo, mload(ptrFrom)) } } } for (uint256 i = 0; i < l1CoordinatorLength; i++) { uint8 v; // L1-Coordinator-Tx bytes[0] bytes32 s; // L1-Coordinator-Tx bytes[1:32] bytes32 r; // L1-Coordinator-Tx bytes[33:64] bytes32 babyPubKey; // L1-Coordinator-Tx bytes[65:96] uint256 tokenID; // L1-Coordinator-Tx bytes[97:100] assembly { v := byte(0, calldataload(dPtr)) dPtr := add(dPtr, 1) s := calldataload(dPtr) dPtr := add(dPtr, 32) r := calldataload(dPtr) dPtr := add(dPtr, 32) babyPubKey := calldataload(dPtr) dPtr := add(dPtr, 32) tokenID := shr(224, calldataload(dPtr)) // 256-32 = 224 dPtr := add(dPtr, 4) } require( tokenID < tokenList.length, "Litex::_buildL1Data: TOKEN_NOT_REGISTERED" ); address ethAddress = _ETH_ADDRESS_INTERNAL_ONLY; // v must be >=27 --> EIP-155, v == 0 means no signature if (v != 0) { ethAddress = _checkSig(babyPubKey, r, s, v); } // add L1-Coordinator-Tx to the L1-tx queue assembly { mstore(ptr, shl(96, ethAddress)) // 256 - 160 = 96, write ethAddress: bytes[0:19] ptr := add(ptr, 20) mstore(ptr, babyPubKey) // write babyPubKey: bytes[20:51] ptr := add(ptr, 32) mstore(ptr, 0) // write zeros // [6 Bytes] fromIdx , // [5 bytes] loadAmountFloat40 . // [5 bytes] amountFloat40 ptr := add(ptr, 16) mstore(ptr, shl(224, tokenID)) // 256 - 32 = 224 write tokenID: bytes[62:65] ptr := add(ptr, 4) mstore(ptr, 0) // write [6 Bytes] toIdx ptr := add(ptr, 6) } } _fillZeros( ptr, (_MAX_L1_TX - l1UserLength - l1CoordinatorLength) * _L1_USER_TOTALBYTES ); } /** * @dev Calculate the circuit input hashing all the elements * @param newLastIdx New total rollup accounts * @param newStRoot New state root * @param newExitRoot New exit root * @param l1Batch Indicates if this forge will be L2 or L1-L2 * @param verifierIdx Verifier index */ function _constructCircuitInput( uint48 newLastIdx, uint256 newStRoot, uint256 newExitRoot, bool l1Batch, uint8 verifierIdx ) internal view returns (uint256) { uint256 oldStRoot = stateRootMap[lastForgedBatch]; uint256 oldLastIdx = lastIdx; uint256 dPtr; // Pointer to the calldata parameter data uint256 dLen; // Length of the calldata parameter // l1L2TxsData = l2Bytes * maxTx = // ([(nLevels / 8) bytes] fromIdx + [(nLevels / 8) bytes] toIdx + [5 bytes] amountFloat40 + [1 bytes] fee) * maxTx = // ((nLevels / 4) bytes + 3 bytes) * maxTx uint256 l1L2TxsDataLength = ((rollupVerifiers[verifierIdx].nLevels / 8) * 2 + 5 + 1) * rollupVerifiers[verifierIdx].maxTx; // [(nLevels / 8) bytes] uint256 feeIdxCoordinatorLength = (rollupVerifiers[verifierIdx] .nLevels / 8) * 64; // the concatenation of all arguments could be done with abi.encodePacked(args), but is suboptimal, especially with a large bytes arrays // [6 bytes] lastIdx + // [6 bytes] newLastIdx + // [32 bytes] stateRoot + // [32 bytes] newStRoot + // [32 bytes] newExitRoot + // [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + // totall1L2TxsDataLength + // feeIdxCoordinatorLength + // [2 bytes] chainID + // [4 bytes] batchNum = // _INPUT_SHA_CONSTANT_BYTES bytes + totall1L2TxsDataLength + feeIdxCoordinatorLength bytes memory inputBytes; uint256 ptr; // Position for writing the bufftr assembly { let inputBytesLength := add( add(_INPUT_SHA_CONSTANT_BYTES, l1L2TxsDataLength), feeIdxCoordinatorLength ) // Set inputBytes to the next free memory space inputBytes := mload(0x40) // Reserve the memory. 32 for the length , the input bytes and 32 // extra bytes at the end for word manipulation mstore(0x40, add(add(inputBytes, 0x40), inputBytesLength)) // Set the actua length of the input bytes mstore(inputBytes, inputBytesLength) // Set The Ptr at the begining of the inputPubber ptr := add(inputBytes, 32) mstore(ptr, shl(208, oldLastIdx)) // 256-48 = 208 ptr := add(ptr, 6) mstore(ptr, shl(208, newLastIdx)) // 256-48 = 208 ptr := add(ptr, 6) mstore(ptr, oldStRoot) ptr := add(ptr, 32) mstore(ptr, newStRoot) ptr := add(ptr, 32) mstore(ptr, newExitRoot) ptr := add(ptr, 32) } // Copy the L1TX Data _buildL1Data(ptr, l1Batch); ptr += _MAX_L1_TX * _L1_USER_TOTALBYTES; // Copy the L2 TX Data from calldata (dPtr, dLen) = _getCallData(4); require( dLen <= l1L2TxsDataLength, "Litex::_constructCircuitInput: L2_TX_OVERFLOW" ); assembly { calldatacopy(ptr, dPtr, dLen) } ptr += dLen; // L2 TX unused data is padded with 0 at the end _fillZeros(ptr, l1L2TxsDataLength - dLen); ptr += l1L2TxsDataLength - dLen; // Copy the FeeIdxCoordinator from the calldata (dPtr, dLen) = _getCallData(5); require( dLen <= feeIdxCoordinatorLength, "Litex::_constructCircuitInput: INVALID_FEEIDXCOORDINATOR_LENGTH" ); assembly { calldatacopy(ptr, dPtr, dLen) } ptr += dLen; _fillZeros(ptr, feeIdxCoordinatorLength - dLen); ptr += feeIdxCoordinatorLength - dLen; // store 2 bytes of chainID at the end of the inputBytes assembly { mstore(ptr, shl(240, chainid())) // 256 - 16 = 240 } ptr += 2; uint256 batchNum = lastForgedBatch + 1; // store 4 bytes of batch number at the end of the inputBytes assembly { mstore(ptr, shl(224, batchNum)) // 256 - 32 = 224 } return uint256(sha256(inputBytes)) % _RFIELD; } /** * @dev Clear the current queue, and update the `nextL1ToForgeQueue` and `nextL1FillingQueue` if needed */ function _clearQueue() internal returns (uint16) { uint16 l1UserTxsLen = uint16( mapL1TxQueue[nextL1ToForgeQueue].length / _L1_USER_TOTALBYTES ); delete mapL1TxQueue[nextL1ToForgeQueue]; nextL1ToForgeQueue++; if (nextL1ToForgeQueue == nextL1FillingQueue) { nextL1FillingQueue++; } return l1UserTxsLen; } /** * @dev Withdraw the funds to the msg.sender if instant withdraw or to the withdraw delayer if delayed * @param amount Amount to retrieve * @param tokenID Token identifier * @param instantWithdraw true if is an instant withdraw */ function _withdrawFunds( uint192 amount, uint32 tokenID, bool instantWithdraw ) internal { if (instantWithdraw) { _safeTransfer(tokenList[tokenID], msg.sender, amount); } else { if (tokenID == 0) { withdrawDelayerContract.deposit{value: amount}( msg.sender, address(0), amount ); } else { address tokenAddress = tokenList[tokenID]; _safeApprove( tokenAddress, address(withdrawDelayerContract), amount ); withdrawDelayerContract.deposit( msg.sender, tokenAddress, amount ); } } } /////////// // helpers ERC20 functions /////////// /** * @dev Approve ERC20 * @param token Token address * @param to Recievers * @param value Quantity of tokens to approve */ function _safeApprove( address token, address to, uint256 value ) internal { /* solhint-disable avoid-low-level-calls */ (bool success, bytes memory data) = token.call( abi.encodeWithSelector(_APPROVE_SIGNATURE, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "Litex::_safeApprove: ERC20_APPROVE_FAILED" ); } /** * @dev Transfer tokens or ether from the smart contract * @param token Token address * @param to Address to recieve the tokens * @param value Quantity to transfer */ function _safeTransfer( address token, address to, uint256 value ) internal { // address 0 is reserved for eth if (token == address(0)) { /* solhint-disable avoid-low-level-calls */ (bool success, ) = msg.sender.call{value: value}(new bytes(0)); require(success, "Litex::_safeTransfer: ETH_TRANSFER_FAILED"); } else { /* solhint-disable avoid-low-level-calls */ (bool success, bytes memory data) = token.call( abi.encodeWithSelector(_TRANSFER_SIGNATURE, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "Litex::_safeTransfer: ERC20_TRANSFER_FAILED" ); } } /** * @dev transferFrom ERC20 * Require approve tokens for this contract previously * @param token Token address * @param from Sender * @param to Reciever * @param value Quantity of tokens to send */ function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(_TRANSFER_FROM_SIGNATURE, from, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "Litex::_safeTransferFrom: ERC20_TRANSFERFROM_FAILED" ); } /////////// // helpers ERC20 extension functions /////////// /** * @notice Function to call token permit method of extended ERC20 * @param _amount Quantity that is expected to be allowed * @param _permitData Raw data of the call `permit` of the token */ function _permit( address token, uint256 _amount, bytes calldata _permitData ) internal { bytes4 sig = abi.decode(_permitData, (bytes4)); require( sig == _PERMIT_SIGNATURE, "LitexAuctionProtocol::_permit: NOT_VALID_CALL" ); ( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) = abi.decode( _permitData[4:], (address, address, uint256, uint256, uint8, bytes32, bytes32) ); require( owner == msg.sender, "Litex::_permit: PERMIT_OWNER_MUST_BE_THE_SENDER" ); require( spender == address(this), "Litex::_permit: SPENDER_MUST_BE_THIS" ); require( value == _amount, "Litex::_permit: PERMIT_AMOUNT_DOES_NOT_MATCH" ); // we call without checking the result, in case it fails and he doesn't have enough balance // the following transferFrom should be fail. This prevents DoS attacks from using a signature // before the smartcontract call /* solhint-disable avoid-low-level-calls */ address(token).call( abi.encodeWithSelector( _PERMIT_SIGNATURE, owner, spender, value, deadline, v, r, s ) ); } }
Update WithdrawalDelay newWithdrawalDelay New WithdrawalDelay Events: `UpdateWithdrawalDelay`/
function updateWithdrawalDelay(uint64 newWithdrawalDelay) external onlyGovernance { require( newWithdrawalDelay <= _MAX_WITHDRAWAL_DELAY, "InstantWithdrawManager::updateWithdrawalDelay: EXCEED_MAX_WITHDRAWAL_DELAY" ); withdrawalDelay = newWithdrawalDelay; emit UpdateWithdrawalDelay(newWithdrawalDelay); }
616,493
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../lib/uniswap/UniswapV2Library.sol"; import "./../lib/uniswap/UniswapV2OracleLibrary.sol"; import "./../lib/uniswap/FixedPoint.sol"; import "./../lib/math/MathUtils.sol"; import "./../external-interfaces/compound-finance/ICToken.sol"; import "./../external-interfaces/compound-finance/IComptroller.sol"; import "./../external-interfaces/compound-finance/IUniswapAnchoredOracle.sol"; import "./../external-interfaces/uniswap/IUniswapV2Router.sol"; import "./CompoundProvider.sol"; import "./../IController.sol"; import "./ICompoundCumulator.sol"; import "./../oracle/IYieldOracle.sol"; import "./../oracle/IYieldOraclelizable.sol"; contract CompoundController is IController, ICompoundCumulator, IYieldOraclelizable { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public constant UNISWAP_ROUTER_V2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 public constant MAX_UINT256 = uint256(-1); uint256 public constant DOUBLE_SCALE = 1e36; uint256 public constant BLOCKS_PER_DAY = 5760; // 4 * 60 * 24 (assuming 4 blocks per minute) uint256 public harvestedLast; // last time we cumulated uint256 public prevCumulationTime; // exchnageRateStored last time we cumulated uint256 public prevExchnageRateCurrent; // cumulative supply rate += ((new underlying) / underlying) uint256 public cumulativeSupplyRate; // cumulative COMP distribution rate += ((new underlying) / underlying) uint256 public cumulativeDistributionRate; // compound.finance comptroller.compSupplyState right after the previous deposit/withdraw IComptroller.CompMarketState public prevCompSupplyState; uint256 public underlyingDecimals; // uniswap path for COMP to underlying address[] public uniswapPath; // uniswap pairs for COMP to underlying address[] public uniswapPairs; // uniswap cumulative prices needed for COMP to underlying uint256[] public uniswapPriceCumulatives; // keys for uniswap cumulativePrice{0 | 1} uint8[] public uniswapPriceKeys; event Harvest(address indexed caller, uint256 compRewardTotal, uint256 compRewardSold, uint256 underlyingPoolShare, uint256 underlyingReward, uint256 harvestCost); modifier onlyPool { require( msg.sender == pool, "CC: only pool" ); _; } constructor( address pool_, address smartYield_, address bondModel_, address[] memory uniswapPath_ ) IController() { pool = pool_; smartYield = smartYield_; underlyingDecimals = ERC20(ICToken(CompoundProvider(pool).cToken()).underlying()).decimals(); setBondModel(bondModel_); setUniswapPath(uniswapPath_); updateAllowances(); } function updateAllowances() public { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IERC20 rewardToken = IERC20(comptroller.getCompAddress()); IERC20 uToken = IERC20(CompoundProvider(pool).uToken()); uint256 routerRewardAllowance = rewardToken.allowance(address(this), uniswapRouter()); rewardToken.safeIncreaseAllowance(uniswapRouter(), MAX_UINT256.sub(routerRewardAllowance)); uint256 poolUnderlyingAllowance = uToken.allowance(address(this), address(pool)); uToken.safeIncreaseAllowance(address(pool), MAX_UINT256.sub(poolUnderlyingAllowance)); } // should start with rewardCToken and with uToken, and have intermediary hops if needed // path[0] = address(rewardCToken); // path[1] = address(wethToken); // path[2] = address(uToken); function setUniswapPath(address[] memory newUniswapPath_) public virtual onlyDao { require( 2 <= newUniswapPath_.length, "CC: setUniswapPath length" ); uniswapPath = newUniswapPath_; address[] memory newUniswapPairs = new address[](newUniswapPath_.length - 1); uint8[] memory newUniswapPriceKeys = new uint8[](newUniswapPath_.length - 1); for (uint256 f = 0; f < newUniswapPath_.length - 1; f++) { newUniswapPairs[f] = UniswapV2Library.pairFor(UNISWAP_FACTORY, newUniswapPath_[f], newUniswapPath_[f + 1]); (address token0, ) = UniswapV2Library.sortTokens(newUniswapPath_[f], newUniswapPath_[f + 1]); newUniswapPriceKeys[f] = token0 == newUniswapPath_[f] ? 0 : 1; } uniswapPairs = newUniswapPairs; uniswapPriceKeys = newUniswapPriceKeys; uniswapPriceCumulatives = uniswapPriceCumulativesNow(); } function uniswapRouter() public view virtual returns(address) { // mockable return UNISWAP_ROUTER_V2; } // claims and sells COMP on uniswap, returns total received comp and caller reward function harvest(uint256 maxCompAmount_) public returns (uint256 compGot, uint256 underlyingHarvestReward) { require( harvestedLast < block.timestamp, "PPC: harvest later" ); ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IERC20 uToken = IERC20(CompoundProvider(pool).uToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IERC20 rewardToken = IERC20(comptroller.getCompAddress()); address caller = msg.sender; // claim pool comp address[] memory holders = new address[](1); holders[0] = pool; address[] memory markets = new address[](1); markets[0] = address(cToken); comptroller.claimComp(holders, markets, false, true); // transfer all comp from pool to self rewardToken.safeTransferFrom(pool, address(this), rewardToken.balanceOf(pool)); uint256 compRewardTotal = rewardToken.balanceOf(address(this)); // COMP // only sell upmost maxCompAmount_, if maxCompAmount_ sell all maxCompAmount_ = (maxCompAmount_ == 0) ? compRewardTotal : maxCompAmount_; uint256 compRewardSold = MathUtils.min(maxCompAmount_, compRewardTotal); require( compRewardSold > 0, "PPC: harvested nothing" ); // pool share is (comp to underlying) - (harvest cost percent) uint256 poolShare = MathUtils.fractionOf( quoteSpotCompToUnderlying(compRewardSold), EXP_SCALE.sub(HARVEST_COST) ); // make sure we get at least the poolShare IUniswapV2Router(uniswapRouter()).swapExactTokensForTokens( compRewardSold, poolShare, uniswapPath, address(this), block.timestamp ); uint256 underlyingGot = uToken.balanceOf(address(this)); require( underlyingGot >= poolShare, "PPC: harvest poolShare" ); // deposit pool reward share with liquidity provider CompoundProvider(pool)._takeUnderlying(address(this), poolShare); CompoundProvider(pool)._depositProvider(poolShare, 0); // pay caller uint256 callerReward = uToken.balanceOf(address(this)); uToken.safeTransfer(caller, callerReward); harvestedLast = block.timestamp; emit Harvest(caller, compRewardTotal, compRewardSold, poolShare, callerReward, HARVEST_COST); return (compRewardTotal, callerReward); } function _beforeCTokenBalanceChange() external override onlyPool { } function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external override onlyPool { // at this point compound.finance state is updated since the pool did a deposit or withdrawl just before, so no need to ping updateCumulativesInternal(prevCTokenBalance_, false); IYieldOracle(oracle).update(); } function providerRatePerDay() public override virtual returns (uint256) { return MathUtils.min( MathUtils.min(BOND_MAX_RATE_PER_DAY, spotDailyRate()), IYieldOracle(oracle).consult(1 days) ); } function cumulatives() external override returns (uint256) { uint256 timeElapsed = block.timestamp - prevCumulationTime; // only cumulate once per block if (0 == timeElapsed) { return cumulativeSupplyRate.add(cumulativeDistributionRate); } uint256 cTokenBalance = CompoundProvider(pool).cTokenBalance(); updateCumulativesInternal(cTokenBalance, true); return cumulativeSupplyRate.add(cumulativeDistributionRate); } function updateCumulativesInternal(uint256 prevCTokenBalance_, bool pingCompound_) private { uint256 timeElapsed = block.timestamp - prevCumulationTime; // only cumulate once per block if (0 == timeElapsed) { return; } ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); uint256[] memory currentUniswapPriceCumulatives = uniswapPriceCumulativesNow(); if (pingCompound_) { // echangeRateStored will be up to date below cToken.accrueInterest(); // compSupplyState will be up to date below comptroller.mintAllowed(address(cToken), address(this), 0); } uint256 exchangeRateStoredNow = cToken.exchangeRateStored(); (uint224 nowSupplyStateIndex, uint32 blk) = comptroller.compSupplyState(address(cToken)); if (prevExchnageRateCurrent > 0) { // cumulate a new supplyRate delta: cumulativeSupplyRate += (cToken.exchangeRateCurrent() - prevExchnageRateCurrent) / prevExchnageRateCurrent // cumulativeSupplyRate eventually overflows, but that's ok due to the way it's used in the oracle cumulativeSupplyRate += exchangeRateStoredNow.sub(prevExchnageRateCurrent).mul(EXP_SCALE).div(prevExchnageRateCurrent); if (prevCTokenBalance_ > 0) { uint256 expectedComp = expectedDistributeSupplierComp(prevCTokenBalance_, nowSupplyStateIndex, prevCompSupplyState.index); uint256 expectedCompInUnderlying = quoteCompToUnderlying( expectedComp, timeElapsed, uniswapPriceCumulatives, currentUniswapPriceCumulatives ); uint256 poolShare = MathUtils.fractionOf(expectedCompInUnderlying, EXP_SCALE.sub(HARVEST_COST)); // cumulate a new distributionRate delta: cumulativeDistributionRate += (expectedDistributeSupplierComp in underlying - harvest cost) / prevUnderlyingBalance // cumulativeDistributionRate eventually overflows, but that's ok due to the way it's used in the oracle cumulativeDistributionRate += poolShare.mul(EXP_SCALE).div(cTokensToUnderlying(prevCTokenBalance_, prevExchnageRateCurrent)); } } prevCumulationTime = block.timestamp; // uniswap cumulatives only change once per block uniswapPriceCumulatives = currentUniswapPriceCumulatives; // compSupplyState changes only once per block prevCompSupplyState = IComptroller.CompMarketState(nowSupplyStateIndex, blk); // exchangeRateStored can increase multiple times per block prevExchnageRateCurrent = exchangeRateStoredNow; } // computes how much COMP tokens compound.finance will have given us after a mint/redeem/redeemUnderlying // source: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol#L1145 function expectedDistributeSupplierComp( uint256 cTokenBalance_, uint224 nowSupplyStateIndex_, uint224 prevSupplyStateIndex_ ) public pure returns (uint256) { uint256 supplyIndex = uint256(nowSupplyStateIndex_); uint256 supplierIndex = uint256(prevSupplyStateIndex_); uint256 deltaIndex = (supplyIndex).sub(supplierIndex); // a - b return (cTokenBalance_).mul(deltaIndex).div(DOUBLE_SCALE); // a * b / doubleScale => uint } function cTokensToUnderlying( uint256 cTokens_, uint256 exchangeRate_ ) public pure returns (uint256) { return cTokens_.mul(exchangeRate_).div(EXP_SCALE); } function uniswapPriceCumulativeNow( address pair_, uint8 priceKey_ ) public view returns (uint256) { (uint256 price0, uint256 price1, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair_); return 0 == priceKey_ ? price0 : price1; } function uniswapPriceCumulativesNow() public view virtual returns (uint256[] memory) { uint256[] memory newUniswapPriceCumulatives = new uint256[](uniswapPairs.length); for (uint256 f = 0; f < uniswapPairs.length; f++) { newUniswapPriceCumulatives[f] = uniswapPriceCumulativeNow(uniswapPairs[f], uniswapPriceKeys[f]); } return newUniswapPriceCumulatives; } function quoteCompToUnderlying( uint256 compIn_, uint256 timeElapsed_, uint256[] memory prevUniswapPriceCumulatives_, uint256[] memory nowUniswapPriceCumulatives_ ) public pure returns (uint256) { uint256 amountIn = compIn_; for (uint256 f = 0; f < prevUniswapPriceCumulatives_.length; f++) { amountIn = uniswapAmountOut(prevUniswapPriceCumulatives_[f], nowUniswapPriceCumulatives_[f], timeElapsed_, amountIn); } return amountIn; } function quoteSpotCompToUnderlying( uint256 compIn_ ) public view virtual returns (uint256) { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(IComptroller(cToken.comptroller()).oracle()); uint256 underlyingOut = compIn_.mul(compOracle.price("COMP")).mul(10**12).div(compOracle.getUnderlyingPrice(address(cToken))); return underlyingOut; } function uniswapAmountOut( uint256 prevPriceCumulative_, uint256 nowPriceCumulative_, uint256 timeElapsed_, uint256 amountIn_ ) public pure returns (uint256) { // per: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol#L93 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((nowPriceCumulative_ - prevPriceCumulative_) / timeElapsed_) ); return FixedPoint.decode144(FixedPoint.mul(priceAverage, amountIn_)); } // compound spot supply rate per day function spotDailySupplyRateProvider() public view returns (uint256) { // supplyRatePerBlock() * BLOCKS_PER_DAY return ICToken(CompoundProvider(pool).cToken()).supplyRatePerBlock().mul(BLOCKS_PER_DAY); } // compound spot distribution rate per day function spotDailyDistributionRateProvider() public view returns (uint256) { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(comptroller.oracle()); // compSpeeds(cToken) * price("COMP") * BLOCKS_PER_DAY uint256 compDollarsPerDay = comptroller.compSpeeds(address(cToken)).mul(compOracle.price("COMP")).mul(BLOCKS_PER_DAY).mul(10**12); // (totalBorrows() + getCash()) * getUnderlyingPrice(cToken) uint256 totalSuppliedDollars = cToken.totalBorrows().add(cToken.getCash()).mul(compOracle.getUnderlyingPrice(address(cToken))); // (compDollarsPerDay / totalSuppliedDollars) return compDollarsPerDay.mul(EXP_SCALE).div(totalSuppliedDollars); } // smart yield spot daily rate includes: spot supply + spot distribution function spotDailyRate() public view returns (uint256) { uint256 expectedSpotDailyDistributionRate = MathUtils.fractionOf(spotDailyDistributionRateProvider(), EXP_SCALE.sub(HARVEST_COST)); // spotDailySupplyRateProvider() + (spotDailyDistributionRateProvider() - fraction lost to harvest) return spotDailySupplyRateProvider().add(expectedSpotDailyDistributionRate); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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) { 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) { // 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) { 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) { 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) { 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) { require(b <= a, "SafeMath: subtraction overflow"); 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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); 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) { require(b > 0, "SafeMath: modulo by zero"); 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) { 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. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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) { 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) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual 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 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 virtual { _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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import './FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import './FullMath.sol'; import './Babylonian.sol'; import './BitMath.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; library MathUtils { using SafeMath for uint256; uint256 public constant EXP_SCALE = 1e18; function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x > y ? x : y; } function compound( // in wei uint256 principal, // rate is * EXP_SCALE uint256 ratePerPeriod, uint16 periods ) internal pure returns (uint256) { if (0 == ratePerPeriod) { return principal; } while (periods > 0) { // principal += principal * ratePerPeriod / EXP_SCALE; principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE)); periods -= 1; } return principal; } function compound2( uint256 principal, uint256 ratePerPeriod, uint16 periods ) internal pure returns (uint256) { if (0 == ratePerPeriod) { return principal; } while (periods > 0) { if (periods % 2 == 1) { //principal += principal * ratePerPeriod / EXP_SCALE; principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE)); periods -= 1; } else { //ratePerPeriod = ((2 * ratePerPeriod * EXP_SCALE) + (ratePerPeriod * ratePerPeriod)) / EXP_SCALE; ratePerPeriod = ((uint256(2).mul(ratePerPeriod).mul(EXP_SCALE)).add(ratePerPeriod.mul(ratePerPeriod))).div(EXP_SCALE); periods /= 2; } } return principal; } // computes a * f / EXP_SCALE function fractionOf(uint256 a, uint256 f) internal pure returns (uint256) { return a.mul(f).div(EXP_SCALE); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface ICToken { function mint(uint mintAmount) external returns (uint256); function redeemUnderlying(uint redeemAmount) external returns (uint256); function accrueInterest() external returns (uint256); function exchangeRateStored() external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function getCash() external view returns (uint256); function underlying() external view returns (address); function comptroller() external view returns (address); } interface ICTokenErc20 { function balanceOf(address to) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IComptroller { struct CompMarketState { uint224 index; uint32 block; } function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) external; function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256); function getCompAddress() external view returns(address); function compSupplyState(address cToken) external view returns (uint224, uint32); function compSpeeds(address cToken) external view returns (uint256); function oracle() external view returns (address); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IUniswapAnchoredOracle { function price(string memory symbol) external view returns (uint256); function getUnderlyingPrice(address cToken) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IUniswapV2Router { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../external-interfaces/compound-finance/ICToken.sol"; import "./../external-interfaces/compound-finance/IComptroller.sol"; import "./CompoundController.sol"; import "./ICompoundCumulator.sol"; import "./../IProvider.sol"; contract CompoundProvider is IProvider { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_UINT256 = uint256(-1); uint256 public constant EXP_SCALE = 1e18; address public override smartYield; address public override controller; // fees colected in underlying uint256 public override underlyingFees; // underlying token (ie. DAI) address public uToken; // IERC20 // claim token (ie. cDAI) address public cToken; // cToken.balanceOf(this) measuring only deposits by users (excludes direct cToken transfers to pool) uint256 public cTokenBalance; uint256 public exchangeRateCurrentCached; uint256 public exchangeRateCurrentCachedAt; bool public _setup; event TransferFees(address indexed caller, address indexed feesOwner, uint256 fees); modifier onlySmartYield { require( msg.sender == smartYield, "PPC: only smartYield" ); _; } modifier onlyController { require( msg.sender == controller, "PPC: only controller" ); _; } modifier onlySmartYieldOrController { require( msg.sender == smartYield || msg.sender == controller, "PPC: only smartYield/controller" ); _; } modifier onlyControllerOrDao { require( msg.sender == controller || msg.sender == CompoundController(controller).dao(), "PPC: only controller/DAO" ); _; } constructor(address cToken_) { cToken = cToken_; uToken = ICToken(cToken_).underlying(); } function setup( address smartYield_, address controller_ ) external { require( false == _setup, "PPC: already setup" ); smartYield = smartYield_; controller = controller_; _enterMarket(); updateAllowances(); _setup = true; } function setController(address newController_) external override onlyControllerOrDao { // remove allowance on old controller IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress()); rewardToken.safeApprove(controller, 0); controller = newController_; // give allowance to new controler updateAllowances(); } function updateAllowances() public { IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress()); uint256 controllerRewardAllowance = rewardToken.allowance(address(this), controller); rewardToken.safeIncreaseAllowance(controller, MAX_UINT256.sub(controllerRewardAllowance)); } // externals // take underlyingAmount_ from from_ function _takeUnderlying(address from_, uint256 underlyingAmount_) external override onlySmartYieldOrController { uint256 balanceBefore = IERC20(uToken).balanceOf(address(this)); IERC20(uToken).safeTransferFrom(from_, address(this), underlyingAmount_); uint256 balanceAfter = IERC20(uToken).balanceOf(address(this)); require( 0 == (balanceAfter - balanceBefore - underlyingAmount_), "PPC: _takeUnderlying amount" ); } // transfer away underlyingAmount_ to to_ function _sendUnderlying(address to_, uint256 underlyingAmount_) external override onlySmartYield { uint256 balanceBefore = IERC20(uToken).balanceOf(to_); IERC20(uToken).safeTransfer(to_, underlyingAmount_); uint256 balanceAfter = IERC20(uToken).balanceOf(to_); require( 0 == (balanceAfter - balanceBefore - underlyingAmount_), "PPC: _sendUnderlying amount" ); } // deposit underlyingAmount_ with the liquidity provider, callable by smartYield or controller function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external override onlySmartYieldOrController { _depositProviderInternal(underlyingAmount_, takeFees_); } // deposit underlyingAmount_ with the liquidity provider, store resulting cToken balance in cTokenBalance function _depositProviderInternal(uint256 underlyingAmount_, uint256 takeFees_) internal { // underlyingFees += takeFees_ underlyingFees = underlyingFees.add(takeFees_); ICompoundCumulator(controller)._beforeCTokenBalanceChange(); IERC20(uToken).approve(address(cToken), underlyingAmount_); uint256 err = ICToken(cToken).mint(underlyingAmount_); require(0 == err, "PPC: _depositProvider mint"); ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance); // cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this)); } // withdraw underlyingAmount_ from the liquidity provider, callable by smartYield function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external override onlySmartYield { _withdrawProviderInternal(underlyingAmount_, takeFees_); } // withdraw underlyingAmount_ from the liquidity provider, store resulting cToken balance in cTokenBalance function _withdrawProviderInternal(uint256 underlyingAmount_, uint256 takeFees_) internal { // underlyingFees += takeFees_; underlyingFees = underlyingFees.add(takeFees_); ICompoundCumulator(controller)._beforeCTokenBalanceChange(); uint256 err = ICToken(cToken).redeemUnderlying(underlyingAmount_); require(0 == err, "PPC: _withdrawProvider redeemUnderlying"); ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance); // cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this)); } function transferFees() external override { _withdrawProviderInternal(underlyingFees, 0); underlyingFees = 0; uint256 fees = IERC20(uToken).balanceOf(address(this)); address to = CompoundController(controller).feesOwner(); IERC20(uToken).safeTransfer(to, fees); emit TransferFees(msg.sender, to, fees); } // current total underlying balance, as measured by pool, without fees function underlyingBalance() external virtual override returns (uint256) { // https://compound.finance/docs#protocol-math // (total balance in underlying) - underlyingFees // cTokenBalance * exchangeRateCurrent() / EXP_SCALE - underlyingFees; return cTokenBalance.mul(exchangeRateCurrent()).div(EXP_SCALE).sub(underlyingFees); } // /externals // public // get exchangeRateCurrent from compound and cache it for the current block function exchangeRateCurrent() public virtual returns (uint256) { // only once per block if (block.timestamp > exchangeRateCurrentCachedAt) { exchangeRateCurrentCachedAt = block.timestamp; exchangeRateCurrentCached = ICToken(cToken).exchangeRateCurrent(); } return exchangeRateCurrentCached; } // /public // internals // call comptroller.enterMarkets() // needs to be called only once BUT before any interactions with the provider function _enterMarket() internal { address[] memory markets = new address[](1); markets[0] = cToken; uint256[] memory err = IComptroller(ICToken(cToken).comptroller()).enterMarkets(markets); require(err[0] == 0, "PPC: _enterMarket"); } // /internals } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "./Governed.sol"; import "./IProvider.sol"; import "./ISmartYield.sol"; abstract contract IController is Governed { uint256 public constant EXP_SCALE = 1e18; address public pool; // compound provider pool address public smartYield; // smartYield address public oracle; // IYieldOracle address public bondModel; // IBondModel address public feesOwner; // fees are sent here // max accepted cost of harvest when converting COMP -> underlying, // if harvest gets less than (COMP to underlying at spot price) - HARVEST_COST%, it will revert. // if it gets more, the difference goes to the harvest caller uint256 public HARVEST_COST = 40 * 1e15; // 4% // fee for buying jTokens uint256 public FEE_BUY_JUNIOR_TOKEN = 3 * 1e15; // 0.3% // fee for redeeming a sBond uint256 public FEE_REDEEM_SENIOR_BOND = 100 * 1e15; // 10% // max rate per day for sBonds uint256 public BOND_MAX_RATE_PER_DAY = 719065000000000; // APY 30% / year // max duration of a purchased sBond uint16 public BOND_LIFE_MAX = 90; // in days bool public PAUSED_BUY_JUNIOR_TOKEN = false; bool public PAUSED_BUY_SENIOR_BOND = false; function setHarvestCost(uint256 newValue_) public onlyDao { require( HARVEST_COST < EXP_SCALE, "IController: HARVEST_COST too large" ); HARVEST_COST = newValue_; } function setBondMaxRatePerDay(uint256 newVal_) public onlyDao { BOND_MAX_RATE_PER_DAY = newVal_; } function setBondLifeMax(uint16 newVal_) public onlyDao { BOND_LIFE_MAX = newVal_; } function setFeeBuyJuniorToken(uint256 newVal_) public onlyDao { FEE_BUY_JUNIOR_TOKEN = newVal_; } function setFeeRedeemSeniorBond(uint256 newVal_) public onlyDao { FEE_REDEEM_SENIOR_BOND = newVal_; } function setPaused(bool buyJToken_, bool buySBond_) public onlyDaoOrGuardian { PAUSED_BUY_JUNIOR_TOKEN = buyJToken_; PAUSED_BUY_SENIOR_BOND = buySBond_; } function setOracle(address newVal_) public onlyDao { oracle = newVal_; } function setBondModel(address newVal_) public onlyDao { bondModel = newVal_; } function setFeesOwner(address newVal_) public onlyDao { feesOwner = newVal_; } function yieldControllTo(address newController_) public onlyDao { IProvider(pool).setController(newController_); ISmartYield(smartYield).setController(newController_); } function providerRatePerDay() external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface ICompoundCumulator { function _beforeCTokenBalanceChange() external; function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IYieldOracle { function update() external; function consult(uint256 forInterval) external returns (uint256 amountOut); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IYieldOraclelizable { // accumulates/updates internal state and returns cumulatives // oracle should call this when updating function cumulatives() external returns(uint256 cumulativeYield); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // 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"); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IProvider { function smartYield() external view returns (address); function controller() external view returns (address); function underlyingFees() external view returns (uint256); // deposit underlyingAmount_ into provider, add takeFees_ to fees function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external; // withdraw underlyingAmount_ from provider, add takeFees_ to fees function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external; function _takeUnderlying(address from_, uint256 amount_) external; function _sendUnderlying(address to_, uint256 amount_) external; function transferFees() external; // current total underlying balance as measured by the provider pool, without fees function underlyingBalance() external returns (uint256); function setController(address newController_) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; abstract contract Governed { address public dao; address public guardian; modifier onlyDao { require( dao == msg.sender, "GOV: not dao" ); _; } modifier onlyDaoOrGuardian { require( msg.sender == dao || msg.sender == guardian, "GOV: not dao/guardian" ); _; } constructor() { dao = msg.sender; guardian = msg.sender; } function setDao(address dao_) external onlyDao { dao = dao_; } function setGuardian(address guardian_) external onlyDao { guardian = guardian_; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface ISmartYield { // a senior BOND (metadata for NFT) struct SeniorBond { // amount seniors put in uint256 principal; // amount yielded at the end. total = principal + gain uint256 gain; // bond was issued at timestamp uint256 issuedAt; // bond matures at timestamp uint256 maturesAt; // was it liquidated yet bool liquidated; } // a junior BOND (metadata for NFT) struct JuniorBond { // amount of tokens (jTokens) junior put in uint256 tokens; // bond matures at timestamp uint256 maturesAt; } // a checkpoint for all JuniorBonds with same maturity date JuniorBond.maturesAt struct JuniorBondsAt { // sum of JuniorBond.tokens for JuniorBonds with the same JuniorBond.maturesAt uint256 tokens; // price at which JuniorBonds will be paid. Initially 0 -> unliquidated (price is in the future or not yet liquidated) uint256 price; } function controller() external view returns (address); function buyBond(uint256 principalAmount_, uint256 minGain_, uint256 deadline_, uint16 forDays_) external returns (uint256); function redeemBond(uint256 bondId_) external; function unaccountBonds(uint256[] memory bondIds_) external; function buyTokens(uint256 underlyingAmount_, uint256 minTokens_, uint256 deadline_) external; /** * sell all tokens instantly */ function sellTokens(uint256 tokens_, uint256 minUnderlying_, uint256 deadline_) external; function buyJuniorBond(uint256 tokenAmount_, uint256 maxMaturesAt_, uint256 deadline_) external; function redeemJuniorBond(uint256 jBondId_) external; function liquidateJuniorBonds(uint256 upUntilTimestamp_) external; /** * token purchase price */ function price() external returns (uint256); function abondPaid() external view returns (uint256); function abondDebt() external view returns (uint256); function abondGain() external view returns (uint256); /** * @notice current total underlying balance, without accruing interest */ function underlyingTotal() external returns (uint256); /** * @notice current underlying loanable, without accruing interest */ function underlyingLoanable() external returns (uint256); function underlyingJuniors() external returns (uint256); function bondGain(uint256 principalAmount_, uint16 forDays_) external returns (uint256); function maxBondDailyRate() external returns (uint256); function setController(address newController_) external; }
withdraw underlyingAmount_ from the liquidity provider, store resulting cToken balance in cTokenBalance underlyingFees += takeFees_; cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls
function _withdrawProviderInternal(uint256 underlyingAmount_, uint256 takeFees_) internal { underlyingFees = underlyingFees.add(takeFees_); ICompoundCumulator(controller)._beforeCTokenBalanceChange(); uint256 err = ICToken(cToken).redeemUnderlying(underlyingAmount_); require(0 == err, "PPC: _withdrawProvider redeemUnderlying"); ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance); cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this)); }
60,074
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "fungible_CDPToken.sol"; import "inheritingForTestPurpose.sol"; // Uniswap Pair Interface interface UniswapV2PairLike { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } // Uniswap Factory Interface interface UniswapV2FactoryLike { function getPair(address tokenA, address tokenB) external view returns (address pair); } // Vat Interface contract VatLike { struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } mapping(bytes32 => Ilk) public ilks; mapping(bytes32 => mapping(address => Urn)) public urns; } interface DSSProxyLike { function execute(address _target, bytes memory _data) external payable returns (bytes32 response); } contract CDPWrapper is inheritingForTestPurpose{ address private owner; mapping(address => uint256) tokenizedCDPs; // Keep track of senders` CDP IDs mapping(uint256 => uint256) tokenization; // Keep track of swap ratios mapping(uint256 => uint256) depts; uint256[] private wrappedCDPs; CDPToken cdp_token; // Token Contract // Maker Dao DssCdpManagerLike private mk_cdpman = DssCdpManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); ProxyRegistryLike private mk_proxy = ProxyRegistryLike(0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4); UniswapV2FactoryLike private us_fac = UniswapV2FactoryLike(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); VatLike private vat = VatLike(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); address private DAI_TOKEN = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address private Wrapped_ETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Only Owner modifier onlyOwner { require(msg.sender==owner, "Not the owner"); _; } constructor() { owner = msg.sender; } /** * @dev Create CDPToken Contract * * The contract required a `CdpTokenizer` to be defined * The `CdpTokenizer` is set to the address of this contract to * permit others minting and burning tokens */ function createTokenContract() public onlyOwner returns(address) { cdp_token = new CDPToken(address(this)); return address(cdp_token); } /** * @dev Update Tokenizer within the Token Contract * * This function allows to flexibly upgrade this Contract * Execute this function after deploying the upgraded contract */ function updateCDPTokenizer(address newtokenizer) public onlyOwner { require(cdp_token.setTokenizer(newtokenizer), "Switch failed"); } /** * @dev Tokenize CDP by transfering ownership and reciving tokens. * * Automatically takes the `sender` first CDP */ function tokenizeCDP() public { // Get Proxy of sender address proxy = mk_proxy.proxies(msg.sender); // Get CDP ID of first Vault uint CDPID = mk_cdpman.first(proxy); address urn = mk_cdpman.urns(CDPID); (, uint256 rate,,,) = vat.ilks(ilk); (uint256 collateral, uint256 dept) = vat.urns(ilk, urn); require(dept*rate/10**27 * 2 < collateral, "CDP not enough collateralized; 200% required"); DSSProxyLike _proxy = DSSProxyLike(proxy); // Make sure that everything that exceeds the 200% collateralization is directly paid back (20 dollar tolerance) if (dept*rate/10**27 * 2 - 20 ether > collateral) { uint256 change = collateral - dept*rate/10**27; } uint256 dai_eth = getExchangeRate(); uint256 amoutToMint = collateral - (dept*rate/10**27/dai_eth); // Differance between collateral in ETH and stablecoin dept in ETH // Create proxy instance and execute the give function through it bytes memory payload = abi.encodeWithSignature("give(uint256,address)", CDPID, address(this)); _proxy.execute(address(mk_cdpman), payload); cdp_token.mint(msg.sender, amoutToMint); depts[CDPID] = amoutToMint; wrappedCDPs.push(CDPID); } /** * @dev Overloaded function, see above. * * Allows to specify a specific CDP by ID */ function tokenizeCDP(uint256 CDPID) public { address urn = mk_cdpman.urns(CDPID); (, uint256 rate,,,) = vat.ilks(ilk); (uint256 collateral, uint256 dept) = vat.urns(ilk, urn); uint256 dai_eth = getExchangeRate(); uint256 amoutToMint = collateral - (dept*rate/10**27/dai_eth); // Differance between collateral in ETH and stablecoin dept in ETH mk_cdpman.give(CDPID, address(this)); cdp_token.mint(msg.sender, amoutToMint); depts[CDPID] = amoutToMint; wrappedCDPs.push(CDPID); } /** * @dev Unlock any CDP without any arguments */ function unlockAnyCDP() public returns(uint256 cdpid){ // Get Token balance of sender uint256 balance = cdp_token.balanceOf(msg.sender); for (uint256 i=0; i<wrappedCDPs.length-1; i++) { if(depts[wrappedCDPs[i]] <= balance) { cdp_token.burn(msg.sender, depts[wrappedCDPs[i]]); // Grant access right of CDP to sender mk_cdpman.give(wrappedCDPs[i], msg.sender); wrappedCDPs[i] = wrappedCDPs[wrappedCDPs.length - 1]; delete wrappedCDPs[wrappedCDPs.length - 1]; wrappedCDPs.pop(); return wrappedCDPs[i]; } } return 0; } /** * @dev Unlock specific CDP by providing its ID */ function unlockspecificCDP(uint256 CDPID) public returns(uint256 cdpid){ // Get Token balance of sender uint256 balance = cdp_token.balanceOf(msg.sender); require(balance >= depts[CDPID], "Not enough tokens to unlock this vault"); cdp_token.burn(msg.sender, depts[CDPID]); // Grant access right of CDP to sender mk_cdpman.give(CDPID, msg.sender); wrappedCDPs[CDPID] = wrappedCDPs[wrappedCDPs.length - 1]; delete wrappedCDPs[wrappedCDPs.length - 1]; wrappedCDPs.pop(); return CDPID; } function getWrappedCDPCount() public view returns(uint count) { return wrappedCDPs.length; } // get Uniswap's exchange rate of DAI/WETH function getExchangeRate() public view returns (uint256) { (uint256 a, uint256 b) = getTokenReserves_uni(); return a / b; } // get token reserves from the pool to determine the current exchange rate function getTokenReserves_uni() public view returns (uint256, uint256) { address pair = us_fac.getPair(DAI_TOKEN, Wrapped_ETH); (uint256 reserve0, uint256 reserve1, ) = UniswapV2PairLike(pair).getReserves(); return (reserve0, reserve1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CDP Interface interface DssCdpManagerLike { function first(address) external returns(uint256); // Owner => First CDPId function urns(uint256) external returns(address); // CDPId => UrnHandler function give(uint cdp, address dst) external; } // Proxy Registry Interface interface ProxyRegistryLike { function proxies(address) external view returns (address); // build proxy contract function build(address owner) external; } contract inheritingForTestPurpose{ ProxyRegistryLike private mk_proxy = ProxyRegistryLike(0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4); address private mk_action = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038; DssCdpManagerLike private mk_cdpman = DssCdpManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address private mk_jug = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address private mk_ethjoin = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address private mk_daijoin = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000; uint256 public cdpi; function buildProxyOpenCdpLockETH() public payable { if (mk_proxy.proxies(msg.sender) == address(0)) { mk_proxy.build(msg.sender); } bytes memory payload = abi.encodeWithSignature( "openLockETHAndDraw(address,address,address,address,bytes32,uint256)", mk_cdpman, mk_jug, mk_ethjoin, mk_daijoin, ilk, 0 ); (bool success, ) = mk_proxy.proxies(msg.sender).call{value: msg.value}(abi.encodeWithSignature("execute(address,bytes)", mk_action, payload )); require(success, "no success"); cdpi = mk_cdpman.first(mk_proxy.proxies(msg.sender)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 * 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 CDPToken is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name = "TokenizedCDP"; string private _symbol = "tCDP"; address private _tokenizer; modifier onlyCdpTokenizer { require(msg.sender==_tokenizer, "Not the Tokenizer"); _; } /** * @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. */ constructor (address tokenizer_) { _tokenizer = tokenizer_; } /** * @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; } /** * @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 this function is * overridden; * * 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 virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } 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] + 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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } 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"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += 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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += 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"); 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This 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 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 mint(address account, uint256 amount) public onlyCdpTokenizer returns (bool) { _mint(account, amount); return true; } function burn(address account, uint256 amount) public onlyCdpTokenizer returns (bool) { _burn(account, amount); return true; } function setTokenizer(address account) public onlyCdpTokenizer returns (bool) { _tokenizer = account; return true; } function tokenizerAddress() public view virtual returns (address) { return _tokenizer; } }
Owner => First CDPId
function first(address) external returns(uint256);
7,218,912
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./libraries/SafeERC20.sol"; import "../utils/Pausable.sol"; import "./libraries/Math.sol"; import "./AdminInterface.sol"; import "./AlphaToken.sol"; import "./DepositNFT.sol"; import "./WithdrawalNFT.sol"; /** * @title AlphaStrategy * @dev Implementation of AlphaStrategy */ contract AlphaStrategy is Pausable { using SafeERC20 for IERC20; using Math for uint256; // Decimal factors uint256 public AMOUNT_SCALE_DECIMALS = 1; // for stable token uint256 public COEFF_SCALE_DECIMALS_F; // for fees uint256 public COEFF_SCALE_DECIMALS_P; // for ALPHA price // Maximum allowed deposit/withdraw amount uint256 public MAX_AMOUNT_DEPOSIT = 1000000 * 1e18; uint256 public MAX_AMOUNT_WITHDRAW = 1000000 * 1e18; // Deposit fee rate uint256 public DEPOSIT_FEE_RATE; // Alpha prices uint256 public ALPHA_PRICE; uint256 public ALPHA_PRICE_WAVG; // Event variables uint public netDepositInd; uint256 public netAmountEvent; uint256 public maxDepositAmount; uint256 public maxWithdrawAmount; uint256 public withdrawAmountTotal; uint256 public withdrawAmountTotalOld; uint256 public depositAmountTotal; uint256 public TIME_WITHDRAW_MANAGER = 0; // ALPHA token data uint256 public totalSupply; // NFT data uint256 tokenIdDeposit; uint256 tokenIdWithdraw; // Other variables for Alpha strategy bool public CAN_CANCEL = false; address public treasury; mapping(address => uint256) public acceptedWithdrawPerAddress; //Contracts AdminInterface public admin; IERC20 public stableToken; AlphaToken public alphaToken; DepositNFT public depositNFT; WithdrawalNFT public withdrawalNFT; constructor(address _admin, address _stableTokenAddress, address _alphaToken, address _depositNFTAdress, address _withdrawalNFTAdress) { require( _admin != address(0), "Formation.Fi: admin address is the zero address" ); require( _stableTokenAddress != address(0), "Formation.Fi: Stable token address is the zero address" ); require( _alphaToken != address(0), "Formation.Fi: ALPHA token address is the zero address" ); require( _depositNFTAdress != address(0), "Formation.Fi: withdrawal NFT address is the zero address" ); require( _withdrawalNFTAdress != address(0), "Formation.Fi: withdrawal NFT address is the zero address" ); admin = AdminInterface(_admin); stableToken = IERC20(_stableTokenAddress); alphaToken = AlphaToken(_alphaToken); depositNFT = DepositNFT(_depositNFTAdress); withdrawalNFT = WithdrawalNFT(_withdrawalNFTAdress); uint8 _stableTokenDecimals = ERC20(_stableTokenAddress).decimals(); if (_stableTokenDecimals == 6) { AMOUNT_SCALE_DECIMALS = 1e12; } } // Modifiers modifier onlyManager() { address _manager = admin.manager(); require(msg.sender == _manager, "Formation.Fi: Caller is not the manager"); _; } modifier canCancel() { bool _CAN_CANCEL = admin.CAN_CANCEL(); require( _CAN_CANCEL == true, "Formation.Fi: Cancel feature is not available"); _; } // Getter functions. function getTVL() public view returns (uint256) { return (admin.ALPHA_PRICE() * alphaToken.totalSupply()) / admin.COEFF_SCALE_DECIMALS_P(); } // Setter functions function set_MAX_AMOUNT_DEPOSIT(uint256 _MAX_AMOUNT_DEPOSIT) external onlyManager { MAX_AMOUNT_DEPOSIT = _MAX_AMOUNT_DEPOSIT; } function set_MAX_AMOUNT_WITHDRAW(uint256 _MAX_AMOUNT_WITHDRAW) external onlyManager{ MAX_AMOUNT_WITHDRAW = _MAX_AMOUNT_WITHDRAW; } function updateAdminData() internal { COEFF_SCALE_DECIMALS_F = admin.COEFF_SCALE_DECIMALS_F(); COEFF_SCALE_DECIMALS_P= admin.COEFF_SCALE_DECIMALS_P(); DEPOSIT_FEE_RATE = admin.DEPOSIT_FEE_RATE(); ALPHA_PRICE = admin.ALPHA_PRICE(); ALPHA_PRICE_WAVG = admin.ALPHA_PRICE_WAVG(); totalSupply = alphaToken.totalSupply(); treasury = admin.treasury(); } // Calculate rebalancing Event parameters function calculateNetDepositInd() public onlyManager { updateAdminData(); netDepositInd = admin.calculateNetDepositInd(depositAmountTotal, withdrawAmountTotal); } function calculateNetAmountEvent() public onlyManager { netAmountEvent = admin.calculateNetAmountEvent(depositAmountTotal, withdrawAmountTotal, MAX_AMOUNT_DEPOSIT, MAX_AMOUNT_WITHDRAW); } function calculateMaxDepositAmount( ) external whenNotPaused onlyManager { if (netDepositInd == 1) { maxDepositAmount = (netAmountEvent + ((withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P)); } else { maxDepositAmount = Math.min(depositAmountTotal, MAX_AMOUNT_DEPOSIT); } } function calculateMaxWithdrawAmount( ) external whenNotPaused onlyManager { withdrawAmountTotalOld = withdrawAmountTotal; maxWithdrawAmount = ((netAmountEvent + depositAmountTotal) * COEFF_SCALE_DECIMALS_P); } function calculateAcceptedWithdrawRequests(address[] memory _users) internal { require (_users.length > 0, "Formation.Fi: no users provided"); uint256 _amountLP; for (uint256 i = 0; i < _users.length; i++) { require( _users[i]!= address(0), "Formation.Fi: user address is the zero address" ); ( , _amountLP, )= withdrawalNFT.pendingWithdrawPerAddress(_users[i]); if (withdrawalNFT.balanceOf( _users[i]) == 0) { continue; } _amountLP = Math.min((maxWithdrawAmount * _amountLP)/( ALPHA_PRICE * withdrawAmountTotalOld), _amountLP); acceptedWithdrawPerAddress[_users[i]] = _amountLP; } } // Validate users deposit requests function finalizeDeposits( address[] memory _users) external whenNotPaused onlyManager { uint256 _amountStable; uint256 _amountStableTotal = 0; uint256 _depositAlpha; uint256 _depositAlphaTotal = 0; uint256 _feeStable; uint256 _feeStableTotal = 0; uint256 _tokenIdDeposit; require (_users.length > 0, "Formation.Fi: no users provided "); for (uint256 i = 0; i < _users.length ; i++) { address _user =_users[i]; ( , _amountStable, )= depositNFT.pendingDepositPerAddress(_user); if (depositNFT.balanceOf(_user) == 0) { continue; } if (maxDepositAmount <= _amountStableTotal) { break; } _tokenIdDeposit = depositNFT.getTokenId(_user); _amountStable = Math.min(maxDepositAmount - _amountStableTotal , _amountStable); _feeStable = (_amountStable * DEPOSIT_FEE_RATE ) / COEFF_SCALE_DECIMALS_F; depositAmountTotal = depositAmountTotal - _amountStable; _feeStableTotal = _feeStableTotal + _feeStable; _depositAlpha = (( _amountStable - _feeStable) * COEFF_SCALE_DECIMALS_P) / ALPHA_PRICE; _depositAlphaTotal = _depositAlphaTotal + _depositAlpha; _amountStableTotal = _amountStableTotal + _amountStable; alphaToken.mint(_user, _depositAlpha); depositNFT.updateDepositData( _user, _tokenIdDeposit, _amountStable, false); alphaToken.addAmountDeposit(_user, _depositAlpha ); alphaToken.addTimeDeposit(_user, block.timestamp); } maxDepositAmount = maxDepositAmount - _amountStableTotal; if (_depositAlphaTotal >0){ ALPHA_PRICE_WAVG = (( totalSupply * ALPHA_PRICE_WAVG) + ( _depositAlphaTotal * ALPHA_PRICE)) / ( totalSupply + _depositAlphaTotal); } admin.updateAlphaPriceWAVG( ALPHA_PRICE_WAVG); if (admin.MANAGEMENT_FEE_TIME() == 0){ admin.updateManagementFeeTime(block.timestamp); } if ( _feeStableTotal >0){ stableToken.safeTransfer( treasury, _feeStableTotal/AMOUNT_SCALE_DECIMALS); } } // Validate users withdrawal requests function finalizeWithdrawals(address[] memory _users) external whenNotPaused onlyManager { uint256 tokensToBurn = 0; uint256 _amountLP; uint256 _amountStable; uint256 _tokenIdWithdraw; calculateAcceptedWithdrawRequests(_users); for (uint256 i = 0; i < _users.length; i++) { address _user =_users[i]; ( , _amountLP, )= withdrawalNFT.pendingWithdrawPerAddress(_user); if (withdrawalNFT.balanceOf(_user) == 0) { continue; } _amountLP = acceptedWithdrawPerAddress[_user]; withdrawAmountTotal = withdrawAmountTotal - _amountLP ; _amountStable = (_amountLP * ALPHA_PRICE) / ( COEFF_SCALE_DECIMALS_P * AMOUNT_SCALE_DECIMALS); stableToken.safeTransfer(_user, _amountStable); _tokenIdWithdraw = withdrawalNFT.getTokenId(_user); withdrawalNFT.updateWithdrawData( _user, _tokenIdWithdraw, _amountLP, false); tokensToBurn = tokensToBurn + _amountLP; alphaToken.updateDepositDataExternal(_user, _amountLP); delete acceptedWithdrawPerAddress[_user]; } if ((tokensToBurn) > 0){ alphaToken.burn(address(this), tokensToBurn); } if (withdrawAmountTotal == 0){ withdrawAmountTotalOld = 0; } } // Make deposit stable token request function depositRequest(uint256 _amount) external whenNotPaused { require(_amount >= admin.MIN_AMOUNT(), "Formation.Fi: amount is lower than the minimum deposit amount"); if (depositNFT.balanceOf(msg.sender)==0){ tokenIdDeposit = tokenIdDeposit +1; depositNFT.mint(msg.sender, tokenIdDeposit, _amount); } else { uint256 _tokenIdDeposit = depositNFT.getTokenId(msg.sender); depositNFT.updateDepositData (msg.sender, _tokenIdDeposit, _amount, true); } depositAmountTotal = depositAmountTotal + _amount; stableToken.safeTransferFrom(msg.sender, address(this), _amount/AMOUNT_SCALE_DECIMALS); } // Cancel deposit stable token request function cancelDepositRequest(uint256 _amount) external whenNotPaused canCancel { uint256 _tokenIdDeposit = depositNFT.getTokenId(msg.sender); require( _tokenIdDeposit > 0, "Formation.Fi: deposit request doesn't exist"); depositNFT.updateDepositData(msg.sender, _tokenIdDeposit, _amount, false); depositAmountTotal = depositAmountTotal - _amount; stableToken.safeTransfer(msg.sender, _amount/AMOUNT_SCALE_DECIMALS); } // Make withdrawal ALPHA token request function withdrawRequest(uint256 _amount) external whenNotPaused { require ( _amount > 0, "Formation Fi: amount is zero"); require(withdrawalNFT.balanceOf(msg.sender) == 0, "Formation.Fi: withdraw request on pending"); require (alphaToken.ChecklWithdrawalRequest(msg.sender, _amount, admin.LOCKUP_PERIOD_USER()), "Formation.Fi: user Position locked"); tokenIdWithdraw = tokenIdWithdraw +1; withdrawalNFT.mint(msg.sender, tokenIdWithdraw, _amount); withdrawAmountTotal = withdrawAmountTotal + _amount; alphaToken.transferFrom(msg.sender, address(this), _amount); } // Cancel withdraw ALPHA token request function cancelWithdrawalRequest( uint256 _amount) external whenNotPaused { require ( _amount > 0, "Formation Fi: amount is zero"); uint256 _tokenIdWithdraw = withdrawalNFT.getTokenId(msg.sender); require( _tokenIdWithdraw > 0, "Formation.Fi: withdraw request doesn't exist"); withdrawalNFT.updateWithdrawData(msg.sender, _tokenIdWithdraw, _amount, false); withdrawAmountTotal = withdrawAmountTotal - _amount; alphaToken.transfer(msg.sender, _amount); } // Withdraw stable tokens from the contract function availableBalanceWithdrawal(uint256 _amount) external whenNotPaused onlyManager { require((block.timestamp - TIME_WITHDRAW_MANAGER) >= admin.LOCKUP_PERIOD_MANAGER(), "Formation.Fi: Manager Position locked"); uint256 _amountScaled = _amount/AMOUNT_SCALE_DECIMALS; require( stableToken.balanceOf(address(this)) >= _amountScaled, "Formation.Fi: requested amount exceeds contract balance" ); TIME_WITHDRAW_MANAGER = block.timestamp; stableToken.safeTransfer(admin.manager(), _amountScaled); } // Send stable tokens to the contract function sendStableTocontract(uint256 _amount) external whenNotPaused onlyManager { require( _amount > 0, "Formation.Fi: amount is zero"); stableToken.safeTransferFrom(msg.sender, address(this), _amount/AMOUNT_SCALE_DECIMALS); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library SafeERC20 { function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall( abi.encodeWithSelector(0x95d89b41) ); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall( abi.encodeWithSelector(0x06fdde03) ); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) public view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall( abi.encodeWithSelector(0x313ce567) ); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(0xa9059cbb, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed" ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(0x23b872dd, from, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed" ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Transaction is not available"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "Transaction is available"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.4; /** * @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); } /** * @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); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./libraries/SafeERC20.sol"; import "../utils/Pausable.sol"; import "./libraries/Math.sol"; import "./AlphaToken.sol"; /** * @title AdminInterface * @dev Implementation of AdminInterface */ contract AdminInterface is Pausable { using SafeERC20 for IERC20; // Decimal factors uint256 public COEFF_SCALE_DECIMALS_F = 1e4; // for fees uint256 public COEFF_SCALE_DECIMALS_P = 1e6; // for price uint256 public AMOUNT_SCALE_DECIMALS = 1; // for stable token // Fees rate uint256 public DEPOSIT_FEE_RATE = 50; // uint256 public MANAGEMENT_FEE_RATE = 200; uint256 public PERFORMANCE_FEE_RATE = 2000; // Fees parameters uint256 public SECONDES_PER_YEAR = 86400 * 365; uint256 public PERFORMANCE_FEES = 0; uint256 public MANAGEMENT_FEES = 0; uint256 public MANAGEMENT_FEE_TIME = 0; // ALPHA price uint256 public ALPHA_PRICE = 1000000; uint256 public ALPHA_PRICE_WAVG = 1000000; // User deposit parameters uint256 public MIN_AMOUNT = 1000 * 1e18; bool public CAN_CANCEL = true; // Withdrawal parameters uint256 public LOCKUP_PERIOD_MANAGER = 2 hours; uint256 public LOCKUP_PERIOD_USER = 0 days; uint256 public TIME_WITHDRAW_MANAGER = 0; // Portfolio management parameters uint public netDepositInd= 0; uint256 public netAmountEvent =0; uint256 public SLIPPAGE_TOLERANCE = 200; address public manager; address public treasury; address public alphaStrategy; //Contracts AlphaToken public alphaToken; IERC20 public stableToken; constructor( address _manager, address _treasury, address _stableTokenAddress, address _alphaToken) { require( _manager != address(0), "Formation.Fi: manager address is the zero address" ); require( _treasury != address(0), "Formation.Fi: treasury address is the zero address" ); require( _stableTokenAddress != address(0), "Formation.Fi: Stable token address is the zero address" ); require( _alphaToken != address(0), "Formation.Fi: ALPHA token address is the zero address" ); manager = _manager; treasury = _treasury; stableToken = IERC20(_stableTokenAddress); alphaToken = AlphaToken(_alphaToken); uint8 _stableTokenDecimals = ERC20( _stableTokenAddress).decimals(); if ( _stableTokenDecimals == 6) { AMOUNT_SCALE_DECIMALS= 1e12; } } // Modifiers modifier onlyAlphaStrategy() { require(alphaStrategy != address(0), "Formation.Fi: alphaStrategy is the zero address" ); require(msg.sender == alphaStrategy, "Formation.Fi: Caller is not the alphaStrategy" ); _; } modifier onlyManager() { require(msg.sender == manager, "Formation.Fi: Caller is not the manager"); _; } modifier canCancel() { require(CAN_CANCEL == true, "Formation Fi: Cancel feature is not available"); _; } // Setter functions function setTreasury(address _treasury) external onlyOwner { require( _treasury != address(0), "Formation.Fi: manager address is the zero address" ); treasury = _treasury; } function setManager(address _manager) external onlyOwner { require( _manager != address(0), "Formation.Fi: manager address is the zero address" ); manager = _manager; } function setAlphaStrategy(address _alphaStrategy) public onlyOwner { require( _alphaStrategy!= address(0), "Formation.Fi: alphaStrategy is the zero address" ); alphaStrategy = _alphaStrategy; } function setCancel(bool _cancel) external onlyManager { CAN_CANCEL = _cancel; } function setLockupPeriodManager(uint256 _lockupPeriodManager) external onlyManager { LOCKUP_PERIOD_MANAGER = _lockupPeriodManager; } function setLockupPeriodUser(uint256 _lockupPeriodUser) external onlyManager { LOCKUP_PERIOD_USER = _lockupPeriodUser; } function setDepositFeeRate(uint256 _rate) external onlyManager { DEPOSIT_FEE_RATE = _rate; } function setManagementFeeRate(uint256 _rate) external onlyManager { MANAGEMENT_FEE_RATE = _rate; } function setPerformanceFeeRate(uint256 _rate) external onlyManager { PERFORMANCE_FEE_RATE = _rate; } function setMinAmount(uint256 _minAmount) external onlyManager { MIN_AMOUNT = _minAmount; } function setCoeffScaleDecimalsFees (uint256 _scale) external onlyManager { require( _scale > 0, "Formation.Fi: decimal fees factor is 0" ); COEFF_SCALE_DECIMALS_F = _scale; } function setCoeffScaleDecimalsPrice (uint256 _scale) external onlyManager { require( _scale > 0, "Formation.Fi: decimal price factor is 0" ); COEFF_SCALE_DECIMALS_P = _scale; } function updateAlphaPrice(uint256 _price) external onlyManager{ require( _price > 0, "Formation.Fi: ALPHA price is 0" ); ALPHA_PRICE = _price; } function updateAlphaPriceWAVG(uint256 _price_WAVG) external onlyAlphaStrategy { require( _price_WAVG > 0, "Formation.Fi: ALPHA price WAVG is 0" ); ALPHA_PRICE_WAVG = _price_WAVG; } function updateManagementFeeTime(uint256 _time) external onlyAlphaStrategy { MANAGEMENT_FEE_TIME = _time; } // Calculate fees function calculatePerformanceFees() external onlyManager { require(PERFORMANCE_FEES == 0, "Formation.Fi: performance fees pending minting"); uint256 _deltaPrice = 0; if (ALPHA_PRICE > ALPHA_PRICE_WAVG) { _deltaPrice = ALPHA_PRICE - ALPHA_PRICE_WAVG; ALPHA_PRICE_WAVG = ALPHA_PRICE; PERFORMANCE_FEES = (alphaToken.totalSupply() * _deltaPrice * PERFORMANCE_FEE_RATE) / (ALPHA_PRICE * COEFF_SCALE_DECIMALS_F); } } function calculateManagementFees() external onlyManager { require(MANAGEMENT_FEES == 0, "Formation.Fi: management fees pending minting"); if (MANAGEMENT_FEE_TIME!= 0){ uint256 _deltaTime; _deltaTime = block.timestamp - MANAGEMENT_FEE_TIME; MANAGEMENT_FEES = (alphaToken.totalSupply() * MANAGEMENT_FEE_RATE * _deltaTime ) /(COEFF_SCALE_DECIMALS_F * SECONDES_PER_YEAR); MANAGEMENT_FEE_TIME = block.timestamp; } } // Mint fees function mintFees() external onlyManager { if ((PERFORMANCE_FEES + MANAGEMENT_FEES) > 0){ alphaToken.mint(treasury, PERFORMANCE_FEES + MANAGEMENT_FEES); PERFORMANCE_FEES = 0; MANAGEMENT_FEES = 0; } } // Calculate protfolio deposit indicator function calculateNetDepositInd(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal) public onlyAlphaStrategy returns( uint) { if ( _depositAmountTotal >= ((_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P)){ netDepositInd = 1 ; } else { netDepositInd = 0; } return netDepositInd; } // Calculate protfolio Amount function calculateNetAmountEvent(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal, uint256 _MAX_AMOUNT_DEPOSIT, uint256 _MAX_AMOUNT_WITHDRAW) public onlyAlphaStrategy returns(uint256) { uint256 _netDeposit; if (netDepositInd == 1) { _netDeposit = _depositAmountTotal - (_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P; netAmountEvent = Math.min( _netDeposit, _MAX_AMOUNT_DEPOSIT); } else { _netDeposit= ((_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P) - _depositAmountTotal; netAmountEvent = Math.min(_netDeposit, _MAX_AMOUNT_WITHDRAW); } return netAmountEvent; } // Protect against Slippage function protectAgainstSlippage(uint256 _withdrawAmount) public onlyManager whenNotPaused returns (uint256) { require(netDepositInd == 0, "Formation.Fi: it is not a slippage case"); require(_withdrawAmount != 0, "Formation.Fi: amount is zero"); uint256 _amount = 0; uint256 _deltaAmount =0; uint256 _slippage = 0; uint256 _alphaAmount = 0; uint256 _balanceAlphaTreasury = alphaToken.balanceOf(treasury); uint256 _balanceStableTreasury = stableToken.balanceOf(treasury) * AMOUNT_SCALE_DECIMALS; if (_withdrawAmount< netAmountEvent){ _amount = netAmountEvent - _withdrawAmount; _slippage = (_amount * COEFF_SCALE_DECIMALS_F ) / netAmountEvent; if (_slippage >= SLIPPAGE_TOLERANCE) { return netAmountEvent; } else { _deltaAmount = Math.min( _amount, _balanceStableTreasury); if ( _deltaAmount > 0){ stableToken.safeTransferFrom(treasury, alphaStrategy, _deltaAmount/AMOUNT_SCALE_DECIMALS); _alphaAmount = (_deltaAmount * COEFF_SCALE_DECIMALS_P)/ALPHA_PRICE; alphaToken.mint(treasury, _alphaAmount); return _amount - _deltaAmount; } else { return _amount; } } } else { _amount = _withdrawAmount - netAmountEvent; _alphaAmount = (_amount * COEFF_SCALE_DECIMALS_P)/ALPHA_PRICE; _alphaAmount = Math.min(_alphaAmount, _balanceAlphaTreasury); if (_alphaAmount >0) { _deltaAmount = (_alphaAmount * ALPHA_PRICE)/COEFF_SCALE_DECIMALS_P; stableToken.safeTransfer(treasury, _deltaAmount/AMOUNT_SCALE_DECIMALS); alphaToken.burn( treasury, _alphaAmount); } if ((_amount - _deltaAmount) > 0) { stableToken.safeTransfer(manager, (_amount - _deltaAmount)/AMOUNT_SCALE_DECIMALS); } } return 0; } // send Stable Tokens to the contract function sendStableTocontract(uint256 _amount) external whenNotPaused onlyManager { require( _amount > 0, "Formation.Fi: amount is zero"); stableToken.safeTransferFrom(msg.sender, address(this), _amount/AMOUNT_SCALE_DECIMALS); } // send Stable Tokens from the contract AlphaStrategy function sendStableFromcontract() external whenNotPaused onlyManager { require(alphaStrategy != address(0), "Formation.Fi: alphaStrategy is the zero address" ); stableToken.safeTransfer(alphaStrategy, stableToken.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/Math.sol"; /** * @title AlphaToken * @dev Implementation of the LP Token "ALPHA". */ contract AlphaToken is ERC20, Ownable { // Proxy address address alphaStrategy; address admin; // Deposit Mapping mapping(address => uint256[]) public amountDepositPerAddress; mapping(address => uint256[]) public timeDepositPerAddress; constructor() ERC20("Formation Fi: ALPHA TOKEN", "ALPHA") {} // Modifiers modifier onlyProxy() { require( (alphaStrategy != address(0)) && (admin != address(0)), "Formation.Fi: proxy is the zero address" ); require( (msg.sender == alphaStrategy) || (msg.sender == admin), "Formation.Fi: Caller is not the proxy" ); _; } modifier onlyAlphaStrategy() { require(alphaStrategy != address(0), "Formation.Fi: alphaStrategy is the zero address" ); require(msg.sender == alphaStrategy, "Formation.Fi: Caller is not the alphaStrategy" ); _; } // Setter functions function setAlphaStrategy(address _alphaStrategy) external onlyOwner { require( _alphaStrategy!= address(0), "Formation.Fi: alphaStrategy is the zero address" ); alphaStrategy = _alphaStrategy; } function setAdmin(address _admin) external onlyOwner { require( _admin!= address(0), "Formation.Fi: admin is the zero address" ); admin = _admin; } function addTimeDeposit(address _account, uint256 _time) external onlyAlphaStrategy { require( _account!= address(0), "Formation.Fi: account is the zero address" ); require( _time!= 0, "Formation.Fi: deposit time is zero" ); timeDepositPerAddress[_account].push(_time); } function addAmountDeposit(address _account, uint256 _amount) external onlyAlphaStrategy { require( _account!= address(0), "Formation.Fi: account is the zero address" ); require( _amount!= 0, "Formation.Fi: deposit amount is zero" ); amountDepositPerAddress[_account].push(_amount); } // functions "mint" and "burn" function mint(address _account, uint256 _amount) external onlyProxy { require( _account!= address(0), "Formation.Fi: account is the zero address" ); require( _amount!= 0, "Formation.Fi: amount is zero" ); _mint(_account, _amount); } function burn(address _account, uint256 _amount) external onlyProxy { require( _account!= address(0), "Formation.Fi: account is the zero address" ); require( _amount!= 0, "Formation.Fi: amount is zero" ); _burn( _account, _amount); } // Check the user lock up condition for his withdrawal request function ChecklWithdrawalRequest(address _account, uint256 _amount, uint256 _period) external view returns (bool){ require( _account!= address(0), "Formation.Fi: account is the zero address" ); require( _amount!= 0, "Formation.Fi: amount is zero" ); uint256 [] memory _amountDeposit = amountDepositPerAddress[_account]; uint256 [] memory _timeDeposit = timeDepositPerAddress[_account]; uint256 _amountTotal = 0; for (uint256 i = 0; i < _amountDeposit.length; i++) { require ((block.timestamp - _timeDeposit[i]) >= _period, "Formation.Fi: user position locked"); if (_amount<= (_amountTotal + _amountDeposit[i])){ break; } _amountTotal = _amountTotal + _amountDeposit[i]; } return true; } // Functions to update users deposit data function updateDepositDataExternal( address _account, uint256 _amount) external onlyAlphaStrategy { updateDepositData(_account, _amount); } function updateDepositData( address _account, uint256 _amount) internal { require( _account!= address(0), "Formation.Fi: account is the zero address" ); require( _amount!= 0, "Formation.Fi: amount is zero" ); uint256 [] memory _amountDeposit = amountDepositPerAddress[ _account]; uint256 _amountlocal = 0; uint256 _amountTotal = 0; uint256 _newAmount; for (uint256 i = 0; i < _amountDeposit.length; i++) { _amountlocal = Math.min(_amountDeposit[i], _amount- _amountTotal); _amountTotal = _amountTotal + _amountlocal; _newAmount = _amountDeposit[i] - _amountlocal; amountDepositPerAddress[_account][i] = _newAmount; if (_newAmount==0){ deleteDepositData(_account, i); } if (_amountTotal == _amount){ break; } } } // Delete deposit data function deleteDepositData(address _account, uint256 _ind) internal { require( _account!= address(0), "Formation.Fi: account is the zero address" ); uint256 size = amountDepositPerAddress[_account].length-1; require( _ind <= size, "Formation.Fi: index is out of the range" ); for (uint256 i = _ind; i< size; i++){ amountDepositPerAddress[ _account][i] = amountDepositPerAddress[ _account][i+1]; timeDepositPerAddress[ _account][i] = timeDepositPerAddress[ _account][i+1]; } amountDepositPerAddress[ _account].pop(); timeDepositPerAddress[ _account].pop(); } function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override{ if ((to != address(0)) && (to != alphaStrategy) && (to != admin) && (from != address(0)) ) { updateDepositData(from, amount); amountDepositPerAddress[to].push(amount); timeDepositPerAddress[to].push(block.timestamp); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/Data.sol"; /** * @title DepositNFT * @dev Implementation of DepositNFT "The deposit Proof" */ contract DepositNFT is ERC721, Ownable { struct PendingDeposit { Data.State state; uint256 amountStable; uint256 listPointer; } // Proxy "alphaStrategy contract address public proxy; // Users deposit data mapping(address => PendingDeposit) public pendingDepositPerAddress; address[] public usersOnPendingDeposit; // NFT mapping mapping(address => uint256) private tokenIdPerAddress; constructor () ERC721 ("Alpha Deposit ", "ALPHA_D"){ } // Modifiers modifier onlyProxy() { require( proxy != address(0), "Formation.Fi: proxy is the zero address" ); require(msg.sender == proxy, "Formation.Fi: Caller is not the proxy"); _; } // Getter functions function getTokenId(address _account) public view returns (uint256) { require( _account!= address(0), "Formation.Fi: account is the zero address" ); return tokenIdPerAddress[_account]; } function getUsersSize() public view returns (uint256) { return usersOnPendingDeposit.length; } function getUsers() public view returns (address[] memory) { return usersOnPendingDeposit; } // Setter functions function setProxy(address _proxy) public onlyOwner { require( _proxy != address(0), "Formation.Fi: proxy is the zero address" ); proxy = _proxy; } // Functions "mint" and "burn" function mint(address _account, uint256 _tokenId, uint256 _amount) external onlyProxy { require (balanceOf(_account) == 0, "Formation.Fi: account has already a deposit NFT"); _safeMint(_account, _tokenId); updateDepositData( _account, _tokenId, _amount, true); } function burn(uint256 tokenId) internal { address owner = ownerOf(tokenId); require (pendingDepositPerAddress[owner].state != Data.State.PENDING, "Formation.Fi: position is on pending"); deleteDepositData(owner); _burn(tokenId); } // Update user deposit data function updateDepositData(address _account, uint256 _tokenId, uint256 _amount, bool add) public onlyProxy { require (_exists(_tokenId), "Formation.Fi: token does not exist"); require (ownerOf(_tokenId) == _account , "Formation.Fi: account is not the token owner"); if( _amount > 0){ if (add){ if(pendingDepositPerAddress[_account].amountStable == 0){ pendingDepositPerAddress[_account].state = Data.State.PENDING; pendingDepositPerAddress[_account].listPointer = usersOnPendingDeposit.length; tokenIdPerAddress[_account] = _tokenId; usersOnPendingDeposit.push(_account); } pendingDepositPerAddress[_account].amountStable = pendingDepositPerAddress[_account].amountStable + _amount; } else { require(pendingDepositPerAddress[_account].amountStable >= _amount, "Formation Fi: amount excedes pending deposit"); uint256 _newAmount = pendingDepositPerAddress[_account].amountStable - _amount; pendingDepositPerAddress[_account].amountStable = _newAmount; if (_newAmount == 0){ pendingDepositPerAddress[_account].state = Data.State.NONE; burn(_tokenId); } } } } // Delete user deposit data function deleteDepositData(address _account) internal { require( _account!= address(0), "Formation.Fi: account is the zero address" ); uint256 _ind = pendingDepositPerAddress[_account].listPointer; address _user = usersOnPendingDeposit[usersOnPendingDeposit.length - 1]; usersOnPendingDeposit[_ind] = _user; pendingDepositPerAddress[_user].listPointer = _ind; usersOnPendingDeposit.pop(); delete pendingDepositPerAddress[_account]; delete tokenIdPerAddress[_account]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { if ((to != address(0)) && (from != address(0))){ require ((to != proxy), "Formation.Fi: destination address cannot be the proxy" ); uint256 indFrom = pendingDepositPerAddress[from].listPointer; pendingDepositPerAddress[to] = pendingDepositPerAddress[from]; pendingDepositPerAddress[from].state = Data.State.NONE; pendingDepositPerAddress[from].amountStable =0; usersOnPendingDeposit[indFrom] = to; tokenIdPerAddress[to] = tokenIdPerAddress[from]; delete pendingDepositPerAddress[from]; delete tokenIdPerAddress[from]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/Data.sol"; /** * @title WithdrawalNFT * @dev Implementation of WithdrawalNFT "The Withdrawal Proof" */ contract WithdrawalNFT is ERC721, Ownable { // Proxy "alphaStrategy contract address proxy; // Users Withdrawal data struct PendingWithdrawal { Data.State state; uint256 amountAlpha; uint256 listPointer; } mapping(address => PendingWithdrawal) public pendingWithdrawPerAddress; address[] public usersOnPendingWithdraw; // NFT mapping mapping(address => uint256) private tokenIdPerAddress; constructor () ERC721 ("Alpha Withdraw", "Alpha_W"){ } // Modifiers modifier onlyProxy() { require( proxy != address(0), "Formation.Fi: proxy is the zero address" ); require(msg.sender == proxy, "Formation.Fi: Caller is not the proxy"); _; } // Getter functions function getTokenId(address _owner) public view returns (uint256) { return tokenIdPerAddress[ _owner]; } function getUsersSize() public view returns (uint256) { return usersOnPendingWithdraw.length; } function getUsers() public view returns (address[] memory) { return usersOnPendingWithdraw; } // Setter functions function setProxy(address _proxy) public onlyOwner { require( _proxy != address(0), "Formation.Fi: proxy is the zero address" ); proxy = _proxy; } // Functions "mint" and "burn" function mint(address _account, uint256 _tokenId, uint256 _amount) external onlyProxy { require (balanceOf( _account) == 0, "Formation.Fi: account has already a withdraw NFT"); _safeMint(_account, _tokenId); tokenIdPerAddress[_account] = _tokenId; updateWithdrawData (_account, _tokenId, _amount, true); } function burn(uint256 tokenId) internal { address owner = ownerOf(tokenId); require (pendingWithdrawPerAddress[owner].state != Data.State.PENDING, "Formation.Fi: position is on pending"); deleteWithdrawData(owner); _burn(tokenId); } // Update user withdraw data function updateWithdrawData (address _account, uint256 _tokenId, uint256 _amount, bool add) public onlyProxy { require (_exists(_tokenId), "Formation Fi: token does not exist"); require (ownerOf(_tokenId) == _account , "Formation.Fi: account is not the token owner"); if( _amount > 0){ if (add){ pendingWithdrawPerAddress[_account].state = Data.State.PENDING; pendingWithdrawPerAddress[_account].amountAlpha = _amount; pendingWithdrawPerAddress[_account].listPointer = usersOnPendingWithdraw.length; usersOnPendingWithdraw.push(_account); } else { require(pendingWithdrawPerAddress[_account].amountAlpha >= _amount, "Formation.Fi: amount excedes pending withdraw"); uint256 _newAmount = pendingWithdrawPerAddress[_account].amountAlpha - _amount; pendingWithdrawPerAddress[_account].amountAlpha = _newAmount; if (_newAmount == 0){ pendingWithdrawPerAddress[_account].state = Data.State.NONE; burn(_tokenId); } } } } // Delete user withdraw data function deleteWithdrawData(address _account) internal { require( _account!= address(0), "Formation.Fi: account is the zero address" ); uint256 _ind = pendingWithdrawPerAddress[_account].listPointer; address _user = usersOnPendingWithdraw[usersOnPendingWithdraw.length -1]; usersOnPendingWithdraw[ _ind] = _user ; pendingWithdrawPerAddress[ _user].listPointer = _ind; usersOnPendingWithdraw.pop(); delete pendingWithdrawPerAddress[_account]; delete tokenIdPerAddress[_account]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { if ((to != address(0)) && (from != address(0))){ require ((to != proxy), "Formation Fi: destination address is the proxy" ); uint256 indFrom = pendingWithdrawPerAddress[from].listPointer; pendingWithdrawPerAddress[to] = pendingWithdrawPerAddress[from]; pendingWithdrawPerAddress[from].state = Data.State.NONE; pendingWithdrawPerAddress[from].amountAlpha =0; usersOnPendingWithdraw[indFrom] = to; tokenIdPerAddress[to] = tokenIdPerAddress[from]; delete pendingWithdrawPerAddress[from]; delete tokenIdPerAddress[from]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/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 * to implement supply mechanisms]. * * 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 * 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, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @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. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @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; } /** * @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 this function is * overridden; * * 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 virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } 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] + 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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * 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: * * - `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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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: * * - `account` 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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(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); 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This 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 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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT 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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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); } /** * @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); } /** * @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 of token that is not own"); 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); } /** * @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 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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library Data { enum State { NONE, PENDING, READY } } // SPDX-License-Identifier: MIT 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; } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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); } } } } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT 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); }
Validate users withdrawal requests
function finalizeWithdrawals(address[] memory _users) external whenNotPaused onlyManager { uint256 tokensToBurn = 0; uint256 _amountLP; uint256 _amountStable; uint256 _tokenIdWithdraw; calculateAcceptedWithdrawRequests(_users); for (uint256 i = 0; i < _users.length; i++) { address _user =_users[i]; ( , _amountLP, )= withdrawalNFT.pendingWithdrawPerAddress(_user); if (withdrawalNFT.balanceOf(_user) == 0) { continue; } _amountLP = acceptedWithdrawPerAddress[_user]; withdrawAmountTotal = withdrawAmountTotal - _amountLP ; _amountStable = (_amountLP * ALPHA_PRICE) / ( COEFF_SCALE_DECIMALS_P * AMOUNT_SCALE_DECIMALS); stableToken.safeTransfer(_user, _amountStable); _tokenIdWithdraw = withdrawalNFT.getTokenId(_user); withdrawalNFT.updateWithdrawData( _user, _tokenIdWithdraw, _amountLP, false); tokensToBurn = tokensToBurn + _amountLP; alphaToken.updateDepositDataExternal(_user, _amountLP); delete acceptedWithdrawPerAddress[_user]; } if ((tokensToBurn) > 0){ alphaToken.burn(address(this), tokensToBurn); } if (withdrawAmountTotal == 0){ withdrawAmountTotalOld = 0; } }
1,652,584
pragma solidity ^0.5.16; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "./Owned.sol"; import "./Pausable.sol"; import "./SafeDecimalMath.sol"; import "./interfaces/IFeePool.sol"; import "./interfaces/ISynth.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IDepot.sol"; import "./MixinResolver.sol"; contract EtherCollateral is Owned, Pausable, ReentrancyGuard, MixinResolver { using SafeMath for uint256; using SafeDecimalMath for uint256; // ========== CONSTANTS ========== //TODO ADD constant back in uint256 /*constant*/ ONE_THOUSAND = SafeDecimalMath.unit() * 1000; uint256 /*constant*/ ONE_HUNDRED = SafeDecimalMath.unit() * 100; uint256 constant SECONDS_IN_A_YEAR = 31536000; // Common Year // Where fees are pooled in sUSD. address constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; // ========== SETTER STATE VARIABLES ========== // The ratio of Collateral to synths issued uint256 public collateralizationRatio = SafeDecimalMath.unit() * 150; // If updated, all outstanding loans will pay this interest rate in on closure of the loan. Default 5% uint256 public interestRate = (5 * SafeDecimalMath.unit()) / 100; uint256 public interestPerSecond = interestRate.div(SECONDS_IN_A_YEAR); // Minting fee for issuing the synths. Default 50 bips. uint256 public issueFeeRate = (5 * SafeDecimalMath.unit()) / 1000; // Maximum amount of sETH that can be issued by the EtherCollateral contract. Default 5000 uint256 public issueLimit = SafeDecimalMath.unit() * 5000; // Minimum amount of ETH to create loan preventing griefing and gas consumption. Min 1ETH = 0.6666666667 sETH uint256 public minLoanSize = SafeDecimalMath.unit() * 1; // Maximum number of loans an account can create uint256 public accountLoanLimit = 50; // If true then any wallet addres can close a loan not just the loan creator. bool public loanLiquidationOpen = false; // Time when remaining loans can be liquidated uint256 public liquidationDeadline; // ========== STATE VARIABLES ========== // The total number of synths issued by the collateral in this contract uint256 public totalIssuedSynths; // Total number of loans ever created uint256 public totalLoansCreated; // Total number of open loans uint256 public totalOpenLoanCount; // Synth loan storage struct struct synthLoanStruct { // Acccount that created the loan address account; // Amount (in collateral token ) that they deposited uint256 collateralAmount; // Amount (in synths) that they issued to borrow uint256 loanAmount; // When the loan was created uint256 timeCreated; // ID for the loan uint256 loanID; // When the loan was paidback (closed) uint256 timeClosed; } // Users Loans by address mapping(address => synthLoanStruct[]) public accountsSynthLoans; // Account Open Loan Counter mapping(address => uint256) public accountOpenLoanCounter; // ========== CONSTRUCTOR ========== constructor(address _owner, address _resolver) public Owned() Pausable(_owner) MixinResolver(_owner, _resolver) { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); liquidationDeadline = now + 92 days; // Time before loans can be liquidated } // ========== SETTERS ========== function setCollateralizationRatio(uint256 ratio) external onlyOwner { require(ratio <= ONE_THOUSAND, "Too high"); require(ratio >= ONE_HUNDRED, "Too low"); collateralizationRatio = ratio; emit CollateralizationRatioUpdated(ratio); } function setInterestRate(uint256 _interestRate) external onlyOwner { require(_interestRate > SECONDS_IN_A_YEAR, "Interest rate cannot be less that the SECONDS_IN_A_YEAR"); require(_interestRate <= SafeDecimalMath.unit(), "Interest cannot be more than 100% APR"); interestRate = _interestRate; interestPerSecond = _interestRate.div(SECONDS_IN_A_YEAR); emit InterestRateUpdated(interestRate); } function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner { issueFeeRate = _issueFeeRate; emit IssueFeeRateUpdated(issueFeeRate); } function setIssueLimit(uint256 _issueLimit) external onlyOwner { issueLimit = _issueLimit; emit IssueLimitUpdated(issueLimit); } function setMinLoanSize(uint256 _minLoanSize) external onlyOwner { minLoanSize = _minLoanSize; emit MinLoanSizeUpdated(minLoanSize); } function setAccountLoanLimit(uint256 _loanLimit) external onlyOwner { uint256 HARD_CAP = 1000; require(_loanLimit < HARD_CAP, "Owner cannot set higher than HARD_CAP"); accountLoanLimit = _loanLimit; emit AccountLoanLimitUpdated(accountLoanLimit); } function setLoanLiquidationOpen(bool _loanLiquidationOpen) external onlyOwner { require(now > liquidationDeadline, "Before liquidation deadline"); loanLiquidationOpen = _loanLiquidationOpen; emit LoanLiquidationOpenUpdated(loanLiquidationOpen); } // ========== PUBLIC VIEWS ========== function getContractInfo() external view returns ( uint256 _collateralizationRatio, uint256 _issuanceRatio, uint256 _interestRate, uint256 _interestPerSecond, uint256 _issueFeeRate, uint256 _issueLimit, uint256 _minLoanSize, uint256 _totalIssuedSynths, uint256 _totalLoansCreated, uint256 _totalOpenLoanCount, uint256 _ethBalance, uint256 _liquidationDeadline, bool _loanLiquidationOpen ) { _collateralizationRatio = collateralizationRatio; _issuanceRatio = issuanceRatio(); _interestRate = interestRate; _interestPerSecond = interestPerSecond; _issueFeeRate = issueFeeRate; _issueLimit = issueLimit; _minLoanSize = minLoanSize; _totalIssuedSynths = totalIssuedSynths; _totalLoansCreated = totalLoansCreated; _totalOpenLoanCount = totalOpenLoanCount; _ethBalance = 0;// address(this).balance; // TODO add support for 0x47 SELFBALANCE, or fix this contract _liquidationDeadline = liquidationDeadline; _loanLiquidationOpen = loanLiquidationOpen; } // returns value of 100 / collateralizationRatio. // e.g. 100/150 = 0.666666666666666667 // or in wei 100000000000000000000/150000000000000000000 = 666666666666666667 function issuanceRatio() public view returns (uint256) { // this Rounds so you get slightly more rather than slightly less // 4999999999999999995000 return ONE_HUNDRED.divideDecimalRound(collateralizationRatio); } function loanAmountFromCollateral(uint256 collateralAmount) public view returns (uint256) { return collateralAmount.multiplyDecimal(issuanceRatio()); } function collateralAmountForLoan(uint256 loanAmount) external view returns (uint256) { return loanAmount.multiplyDecimal(collateralizationRatio.divideDecimalRound(ONE_HUNDRED)); } function currentInterestOnLoan(address _account, uint256 _loanID) external view returns (uint256) { // Get the loan from storage synthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); uint256 loanLifeSpan = _loanLifeSpan(synthLoan); return accruedInterestOnLoan(synthLoan.loanAmount, loanLifeSpan); } function accruedInterestOnLoan(uint256 _loanAmount, uint256 _seconds) public view returns (uint256 interestAmount) { // Simple interest calculated per second // Interest = Principal * rate * time interestAmount = _loanAmount.multiplyDecimalRound(interestPerSecond.mul(_seconds)); } function calculateMintingFee(address _account, uint256 _loanID) external view returns (uint256) { // Get the loan from storage synthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); return _calculateMintingFee(synthLoan); } function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) { synthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 _counter = 0; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[_counter] = synthLoans[i].loanID; _counter++; } } // Create the fixed size array to return uint256[] memory _result = new uint256[](_counter); // Copy loanIDs from dynamic array to fixed array for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; } // Return an array with list of open Loan IDs return _result; } function getLoan(address _account, uint256 _loanID) external view returns ( address account, uint256 collateralAmount, uint256 loanAmount, uint256 timeCreated, uint256 loanID, uint256 timeClosed, uint256 interest, uint256 totalFees ) { synthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); account = synthLoan.account; collateralAmount = synthLoan.collateralAmount; loanAmount = synthLoan.loanAmount; timeCreated = synthLoan.timeCreated; loanID = synthLoan.loanID; timeClosed = synthLoan.timeClosed; interest = accruedInterestOnLoan(synthLoan.loanAmount, _loanLifeSpan(synthLoan)); totalFees = interest.add(_calculateMintingFee(synthLoan)); } function loanLifeSpan(address _account, uint256 _loanID) external view returns (uint256 loanLifeSpanResult) { synthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); loanLifeSpanResult = _loanLifeSpan(synthLoan); } // ========== PUBLIC FUNCTIONS ========== function openLoan() external payable notPaused nonReentrant returns (uint256 loanID) { // Require ETH sent to be greater than minLoanSize require(msg.value >= minLoanSize, "Not enough ETH to create this loan. Please see the minLoanSize"); // Require loanLiquidationOpen to be false or we are in liquidation phase require(loanLiquidationOpen == false, "Loans are now being liquidated"); // Each account is limted to creating 50 (accountLoanLimit) loans require(accountsSynthLoans[msg.sender].length < accountLoanLimit, "Each account is limted to 50 loans"); // Calculate issuance amount uint256 loanAmount = loanAmountFromCollateral(msg.value); // Require sETH to mint does not exceed cap require(totalIssuedSynths.add(loanAmount) < issueLimit, "Loan Amount exceeds the supply cap. "); // Get a Loan ID loanID = _incrementTotalLoansCounter(); // Create Loan storage object synthLoanStruct memory synthLoan = synthLoanStruct({ account: msg.sender, collateralAmount: msg.value, loanAmount: loanAmount, timeCreated: now, loanID: loanID, timeClosed: 0 }); // Record loan in mapping to account in an array of the accounts open loans accountsSynthLoans[msg.sender].push(synthLoan); // Increment totalIssuedSynths totalIssuedSynths = totalIssuedSynths.add(loanAmount); // Issue the synth synthsETH().issue(msg.sender, loanAmount); // Tell the Dapps a loan was created emit LoanCreated(msg.sender, loanID, loanAmount); } function closeLoan(uint256 loanID) external nonReentrant { _closeLoan(msg.sender, loanID); } // Liquidation of an open loan available for anyone function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external nonReentrant { require(loanLiquidationOpen, "Liquidation is not open"); // Close the creators loan and send collateral to the closer. _closeLoan(_loanCreatorsAddress, _loanID); // Tell the Dapps this loan was liquidated emit LoanLiquidated(_loanCreatorsAddress, _loanID, msg.sender); } // ========== PRIVATE FUNCTIONS ========== function _closeLoan(address account, uint256 loanID) private { // Get the loan from storage synthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); require(synthLoan.loanID > 0, "Loan does not exist"); require(synthLoan.timeClosed == 0, "Loan already closed"); require( synthsETH().balanceOf(msg.sender) >= synthLoan.loanAmount, "You do not have the required Synth balance to close this loan." ); // Record loan as closed _recordLoanClosure(synthLoan); // Decrement totalIssuedSynths totalIssuedSynths = totalIssuedSynths.sub(synthLoan.loanAmount); // Calculate and deduct interest(5%) and minting fee(50 bips) in ETH uint256 interestAmount = accruedInterestOnLoan(synthLoan.loanAmount, _loanLifeSpan(synthLoan)); uint256 mintingFee = _calculateMintingFee(synthLoan); uint256 totalFees = interestAmount.add(mintingFee); // Burn all Synths issued for the loan synthsETH().burn(account, synthLoan.loanAmount); // Fee Distribution. Purchase sUSD with ETH from Depot require(synthsUSD().balanceOf(address(depot())) >= totalFees, "The sUSD Depot does not have enough sUSD to buy for fees"); depot().exchangeEtherForSynths.value(totalFees)(); // Transfer the sUSD to distribute to SNX holders. synthsUSD().transfer(FEE_ADDRESS, synthsUSD().balanceOf(address(this))); // Send remainder ETH to caller address(msg.sender).transfer(synthLoan.collateralAmount.sub(totalFees)); // Tell the Dapps emit LoanClosed(account, loanID, totalFees); } function _getLoanFromStorage(address account, uint256 loanID) private view returns (synthLoanStruct memory) { synthLoanStruct[] memory synthLoans = accountsSynthLoans[account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == loanID) { return synthLoans[i]; } } } function _recordLoanClosure(synthLoanStruct memory synthLoan) private { // Get storage pointer to the accounts array of loans synthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == synthLoan.loanID) { // Record the time the loan was closed synthLoans[i].timeClosed = now; } } // Reduce Total Open Loans Count totalOpenLoanCount = totalOpenLoanCount.sub(1); } function _incrementTotalLoansCounter() private returns (uint256) { // Increase the total Open loan count totalOpenLoanCount = totalOpenLoanCount.add(1); // Increase the total Loans Created count totalLoansCreated = totalLoansCreated.add(1); // Return total count to be used as a unique ID. return totalLoansCreated; } function _calculateMintingFee(synthLoanStruct memory synthLoan) private view returns (uint256 mintingFee) { mintingFee = synthLoan.loanAmount.multiplyDecimalRound(issueFeeRate); } function _loanLifeSpan(synthLoanStruct memory synthLoan) private view returns (uint256 loanLifeSpanResult) { // Get time loan is open for, and if closed from the timeClosed bool loanClosed = synthLoan.timeClosed > 0; // Calculate loan life span in seconds as (Now - Loan creation time) loanLifeSpanResult = loanClosed ? synthLoan.timeClosed.sub(synthLoan.timeCreated) : now.sub(synthLoan.timeCreated); } /* ========== INTERNAL VIEWS ========== */ function synthsETH() internal view returns (ISynth) { return ISynth(resolver.requireAndGetAddress("SynthsETH", "Missing SynthsETH address")); } function synthsUSD() internal view returns (ISynth) { return ISynth(resolver.requireAndGetAddress("SynthsUSD", "Missing SynthsUSD address")); } function depot() internal view returns (IDepot) { return IDepot(resolver.requireAndGetAddress("Depot", "Missing Depot address")); } // ========== EVENTS ========== event CollateralizationRatioUpdated(uint256 ratio); event InterestRateUpdated(uint256 interestRate); event IssueFeeRateUpdated(uint256 issueFeeRate); event IssueLimitUpdated(uint256 issueLimit); event MinLoanSizeUpdated(uint256 minLoanSize); event AccountLoanLimitUpdated(uint256 loanLimit); event LoanLiquidationOpenUpdated(bool loanLiquidationOpen); event LoanCreated(address indexed account, uint256 loanID, uint256 amount); event LoanClosed(address indexed account, uint256 loanID, uint256 feesPaid); event LoanLiquidated(address indexed account, uint256 loanID, address liquidator); }
Get the loan from storage Record loan as closed Decrement totalIssuedSynths Calculate and deduct interest(5%) and minting fee(50 bips) in ETH Burn all Synths issued for the loan Fee Distribution. Purchase sUSD with ETH from Depot Transfer the sUSD to distribute to SNX holders. Send remainder ETH to caller Tell the Dapps
function _closeLoan(address account, uint256 loanID) private { synthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); require(synthLoan.loanID > 0, "Loan does not exist"); require(synthLoan.timeClosed == 0, "Loan already closed"); require( synthsETH().balanceOf(msg.sender) >= synthLoan.loanAmount, "You do not have the required Synth balance to close this loan." ); _recordLoanClosure(synthLoan); totalIssuedSynths = totalIssuedSynths.sub(synthLoan.loanAmount); uint256 interestAmount = accruedInterestOnLoan(synthLoan.loanAmount, _loanLifeSpan(synthLoan)); uint256 mintingFee = _calculateMintingFee(synthLoan); uint256 totalFees = interestAmount.add(mintingFee); synthsETH().burn(account, synthLoan.loanAmount); require(synthsUSD().balanceOf(address(depot())) >= totalFees, "The sUSD Depot does not have enough sUSD to buy for fees"); depot().exchangeEtherForSynths.value(totalFees)(); synthsUSD().transfer(FEE_ADDRESS, synthsUSD().balanceOf(address(this))); address(msg.sender).transfer(synthLoan.collateralAmount.sub(totalFees)); emit LoanClosed(account, loanID, totalFees); }
13,019,966
/** *Submitted for verification at Etherscan.io on 2022-02-02 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // (c) by Mario, Santa Cruz - España. interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ /* slim function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; */ /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they may be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ /* function balanceOf( address _owner ) external view returns (uint256); */ /** * @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are * considered invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. * @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); }interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } contract SupportsInterface is ERC165 { /** * @dev Mapping of supported intefraces. You must not set element 0xffffffff to true. */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev Contract constructor. */ constructor() { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /** * @dev Function to check which interfaces are suported by this contract. * @param _interfaceID Id of the interface. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external override view returns (bool) { return supportedInterfaces[_interfaceID]; } } library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. * @return addressCheck True if _addr is a contract, false if not. */ function isContract( address _addr ) internal view returns (bool addressCheck) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); } } interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. * @return _name Representing name. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. * @return _symbol Representing symbol. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external view returns (string memory); } contract NFToken is ERC721, SupportsInterface { using AddressUtils for address; /** * @dev List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant ZERO_ADDRESS = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008"; /** * @dev Magic value of a smart contract that can receive NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApproval; /** * @dev Mapping from owner address to count of his tokens. */ //mapping (address => uint256) private ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_OR_OPERATOR ); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_APPROVED_OR_OPERATOR ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; } /** * @dev Contract constructor. */ constructor() { supportedInterfaces[0x80ac58cd] = true; // ERC721 //owner = msg.sender; } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ /* slim function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external override { _safeTransferFrom(_from, _to, _tokenId, _data); } */ /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external override { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they may be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external override canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external override canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, IS_OWNER); idToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external override { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ /* slim function balanceOf( address _owner ) external override view returns (uint256) { require(_owner != address(0), ZERO_ADDRESS); return _getOwnerNFTCount(_owner); } */ /** * @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are * considered invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return _owner Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external override view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0), NOT_VALID_NFT); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (address) { return idToApproval[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external override view returns (bool) { return ownerToOperators[_owner][_operator]; } /** * @dev Actually performs the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) internal { address from = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(from, _tokenId); _addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal virtual { require(_to != address(0), ZERO_ADDRESS); require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); _addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external burn * function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ /* slim function _burn( uint256 _tokenId ) internal virtual validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); } */ /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from which we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; } /** * @dev Assigns a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to which we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; } function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) private canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval( uint256 _tokenId ) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } } /** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */ contract NFTokenCollection is NFToken, ERC721Metadata { string internal nftName; string internal nftSymbol; uint256 public nftTokenIdLast = 0; //mapping (uint256 => string) internal idToUri; address payable public owner; string public baseURI; mapping(address => bool) private whiteList; uint256 constant public MAX_SUPPLY = 10000; event newTokenMinted( uint newNFT ); /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumarable nftName = "CATS SAGA CLUB"; nftSymbol = "CATS-SAGA-CLUB"; owner = payable(msg.sender); /* Vealed Ipfs TMP Images */ baseURI = "ipfs://QmUwhHW3XpbCHYkEsxr8RKJihD5qH5WZeYkvTpqFj5akzV/"; whiteList[msg.sender]=true; } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } function mint( address _to, uint256 _tokenId //,string memory _uri ) internal { _mint(_to, _tokenId); } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return string(abi.encodePacked(baseURI,uintToString(_tokenId))); } function uintToString(uint v) internal pure returns (string memory) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = bytes1(uint8(48 + remainder)); } bytes memory s = new bytes(i); // i + 1 is inefficient for (uint j = 0; j < i; j++) { s[j] = reversed[i - j - 1]; // to avoid the off-by-one error } string memory str = string(s); // memory isn't implicitly convertible to storage return str; } /* CONTRACT CUSTOM FUNCTIONS*/ function includeToPrivateWhiteList(address[] memory _users) public { require(msg.sender==owner,"Only approved staff can act here"); for(uint8 i = 0; i < _users.length; i++) { whiteList[_users[i]] = true; } } function buyTokenNFT (uint256 _numTokens) external payable returns (bool success){ uint256 amount = msg.value; uint256 tokenPrice; require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available"); require (_numTokens <= 10 ,"Max 10 Mints each transaction"); if(whiteList[msg.sender]){ tokenPrice = 0.02 ether; }else{ tokenPrice = 0.03 ether; } require(amount >= tokenPrice * _numTokens,"Not enought amount to buy this NFT"); owner.transfer(amount); for(uint i = 0; i < _numTokens; i++){ nftTokenIdLast += 1; mint(msg.sender,nftTokenIdLast); } emit newTokenMinted(nftTokenIdLast); return true; } /*reveal the collection*/ function setBaseURIpfs (string memory _baseUri) external returns (bool success){ require(msg.sender==owner,"Only Admin can act this operation"); baseURI = _baseUri; return true; } /* Mint NFTs for the team*/ function mintTokenAdmin (uint256 _numTokens) external returns (bool success){ require(msg.sender==owner,"Only Admin can act this operation"); require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available"); for(uint i = 0; i < _numTokens; i++){ nftTokenIdLast += 1; mint(msg.sender,nftTokenIdLast); } emit newTokenMinted(nftTokenIdLast); return true; } function totalSupply()public view returns (uint256) { return nftTokenIdLast; } }
mapping (uint256 => string) internal idToUri;
{ string internal nftName; string internal nftSymbol; uint256 public nftTokenIdLast = 0; address payable public owner; string public baseURI; mapping(address => bool) private whiteList; uint256 constant public MAX_SUPPLY = 10000; event newTokenMinted( uint newNFT ); constructor() { nftName = "CATS SAGA CLUB"; nftSymbol = "CATS-SAGA-CLUB"; owner = payable(msg.sender); whiteList[msg.sender]=true; } function name() external override view returns (string memory _name) { _name = nftName; } function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } function mint( address _to, uint256 _tokenId ) internal { _mint(_to, _tokenId); } function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return string(abi.encodePacked(baseURI,uintToString(_tokenId))); } function uintToString(uint v) internal pure returns (string memory) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = bytes1(uint8(48 + remainder)); } for (uint j = 0; j < i; j++) { } return str; } function uintToString(uint v) internal pure returns (string memory) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = bytes1(uint8(48 + remainder)); } for (uint j = 0; j < i; j++) { } return str; } function uintToString(uint v) internal pure returns (string memory) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = bytes1(uint8(48 + remainder)); } for (uint j = 0; j < i; j++) { } return str; } function includeToPrivateWhiteList(address[] memory _users) public { require(msg.sender==owner,"Only approved staff can act here"); for(uint8 i = 0; i < _users.length; i++) { whiteList[_users[i]] = true; } } function includeToPrivateWhiteList(address[] memory _users) public { require(msg.sender==owner,"Only approved staff can act here"); for(uint8 i = 0; i < _users.length; i++) { whiteList[_users[i]] = true; } } function buyTokenNFT (uint256 _numTokens) external payable returns (bool success){ uint256 amount = msg.value; uint256 tokenPrice; require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available"); require (_numTokens <= 10 ,"Max 10 Mints each transaction"); if(whiteList[msg.sender]){ tokenPrice = 0.02 ether; tokenPrice = 0.03 ether; } require(amount >= tokenPrice * _numTokens,"Not enought amount to buy this NFT"); owner.transfer(amount); for(uint i = 0; i < _numTokens; i++){ nftTokenIdLast += 1; mint(msg.sender,nftTokenIdLast); } emit newTokenMinted(nftTokenIdLast); return true; } function buyTokenNFT (uint256 _numTokens) external payable returns (bool success){ uint256 amount = msg.value; uint256 tokenPrice; require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available"); require (_numTokens <= 10 ,"Max 10 Mints each transaction"); if(whiteList[msg.sender]){ tokenPrice = 0.02 ether; tokenPrice = 0.03 ether; } require(amount >= tokenPrice * _numTokens,"Not enought amount to buy this NFT"); owner.transfer(amount); for(uint i = 0; i < _numTokens; i++){ nftTokenIdLast += 1; mint(msg.sender,nftTokenIdLast); } emit newTokenMinted(nftTokenIdLast); return true; } }else{ function buyTokenNFT (uint256 _numTokens) external payable returns (bool success){ uint256 amount = msg.value; uint256 tokenPrice; require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available"); require (_numTokens <= 10 ,"Max 10 Mints each transaction"); if(whiteList[msg.sender]){ tokenPrice = 0.02 ether; tokenPrice = 0.03 ether; } require(amount >= tokenPrice * _numTokens,"Not enought amount to buy this NFT"); owner.transfer(amount); for(uint i = 0; i < _numTokens; i++){ nftTokenIdLast += 1; mint(msg.sender,nftTokenIdLast); } emit newTokenMinted(nftTokenIdLast); return true; } function setBaseURIpfs (string memory _baseUri) external returns (bool success){ require(msg.sender==owner,"Only Admin can act this operation"); baseURI = _baseUri; return true; } function mintTokenAdmin (uint256 _numTokens) external returns (bool success){ require(msg.sender==owner,"Only Admin can act this operation"); require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available"); for(uint i = 0; i < _numTokens; i++){ nftTokenIdLast += 1; mint(msg.sender,nftTokenIdLast); } emit newTokenMinted(nftTokenIdLast); return true; } function mintTokenAdmin (uint256 _numTokens) external returns (bool success){ require(msg.sender==owner,"Only Admin can act this operation"); require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available"); for(uint i = 0; i < _numTokens; i++){ nftTokenIdLast += 1; mint(msg.sender,nftTokenIdLast); } emit newTokenMinted(nftTokenIdLast); return true; } function totalSupply()public view returns (uint256) { return nftTokenIdLast; } }
6,807,683
/** *Submitted for verification at Etherscan.io on 2022-01-06 */ // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @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); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @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); } /** * @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); } /** * @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 of token that is not own"); 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); } /** * @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 {} } // File: contracts/LeAnime2Simplified_RELEASEDAY/Anime2-wrapper_13_stripped_down_FINAL.sol pragma solidity ^0.8.10; /// Le Anime Phase 2 by toomuchlag interface IMerger { function heroURI(uint256 tokenId) external view returns (string memory); } interface ITokenURICustom { function constructTokenURI(uint256 tokenId) external view returns (string memory); } contract LeAnime_Phase2_Wrapper is ERC721, Ownable { using Strings for uint256; // ERC-2981: NFT Royalty Standard bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; address payable private _royaltyRecipient; uint256 private _royaltyBps; uint256 private constant OFFSETNG = 12800010000; uint256 private constant OFFSETAN2 = 100000; uint256 private constant OFFSET_SPIRITS = 1573; //IERC721metadata to reference Le Anime OE NFT tokens IERC721Metadata public mainToken = IERC721Metadata(0x41113bcE4659cB4912ED61d48154839F75131d7A); //address of the mergeContract - able to lock the tokens in this contract when creating Heroes address public mergeContract; //addres of the initial spirits minter contract address public minterContract; //this is to select what "Wrapped Anime" shows, the soul or the walking man video mapping(uint256 => bool) public uriSelection; //optional customURI contract for upgradability address private _customURIContract; //bools to close some upgradable aspects forever bool public closedMergeContractUpdate = false; bool public closedUriUpdate = false; bool public closedMinterUpdate = false; bool public closedMergeActiveUpdate = false; bool public emergencyRevoked = false; bool public mergeActive = false; //baseURI for souls and spirits JSON metadata string public baseURI = "ipfs://ipfs/QmfM9ajo9WybPcrSHJrDRS7Cr9D21mRW52DaBmXK1vEp4p/"; string public baseURI_OE = "https://leanime.art/metadataphase2/oe/"; string public preheroURI = "https://leanime.art/metadataphase2/prehero"; uint256 constant animeFirst = 1; uint256 constant animeLast = 1573; uint256 constant spiritsFirst = 1574; uint256 constant spiritsLast = 10627; constructor(address mainTkn) ERC721("Le Anime by toomuchlag", "LAG") { // set original Le Anime OE token for wrapping; mainToken = IERC721Metadata(mainTkn); _royaltyRecipient = payable(0x50b88F3f1Ea8948731c6af4C0EBfDEf1beccD6Fa); _royaltyBps = 1000; } //register interfaceID _INTERFACE_ID_ERC2981 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return interfaceId == _INTERFACE_ID_ERC2981 || super.supportsInterface(interfaceId); } // *** Token URI functions *** function setBaseURI(string calldata newBaseURI, string calldata newBaseURI_OE) public onlyOwner { require(closedUriUpdate == false, "Uri finalised"); baseURI = newBaseURI; baseURI_OE = newBaseURI_OE; } function setCustomURI(address contractURI) public onlyOwner { require(closedUriUpdate == false, "Uri finalised"); _customURIContract = contractURI; } //flips the tokenURI from soul to walking hero and back - only for le Anime OE function flipURI(uint256 tokenId) public { require(tokenId >= OFFSETAN2 + 1 && tokenId <= OFFSETAN2 + 1573, "Only Le Anime"); require(msg.sender == ownerOf(tokenId), "You are not the owner"); uriSelection[tokenId] = !uriSelection[tokenId]; } //return URI for Anime, Spirits and HEROES - UPGRADABLE function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); //custom URI section to allow extensions at future stage if(_customURIContract != address(0)) { return ITokenURICustom(_customURIContract).constructTokenURI(tokenId); } else { //default token URI section //Le Anime and Spirits Section if(tokenId > OFFSETAN2) { //&& !heroLocked[heroId] if(uriSelection[tokenId]) { //just possible for Le Anime OE - cannot flipURI in spirits return string(abi.encodePacked(baseURI_OE, tokenId.toString())); } return string(abi.encodePacked(baseURI, tokenId.toString())); } else { if(mergeActive) { return IMerger(mergeContract).heroURI(tokenId); } else { return preheroURI; } } } } // *** Admin functions *** ONLY OWNER function closeMergeContractUpdate() onlyOwner public { closedMergeContractUpdate = true; } function closeMergeActiveUpdate() onlyOwner public { closedMergeActiveUpdate = true; } function closeMinterUpdate() onlyOwner public { closedMinterUpdate = true; } function closeUriUpdate() onlyOwner public { closedUriUpdate = true; } function setMergeActive(bool flag) onlyOwner public { require(!closedMergeActiveUpdate, "Cannot update"); mergeActive = flag; } // set the merge Contract function setMergeContract(address mergeContractAddress) public onlyOwner { require(!closedMergeContractUpdate, "Cannot update merge"); mergeContract = mergeContractAddress; } // set the initial mint/claim Contract function setMinterContract(address minterContractAddress) public onlyOwner { require(!closedMinterUpdate, "Cannot update minter"); minterContract = minterContractAddress; } //this revokes the temporary emergency function to recover lost tokens - only smart contract owner can trigger it function revokeEmergency() onlyOwner public { emergencyRevoked = true; } // *** EMERGENCY functions *** emergency withdrawal to recover stuck external ERC721 sent to the contract accidentally function emergencyRecover(address to, address contractAddress, uint256 tokenId) public onlyOwner { require(emergencyRevoked == false, "Emergency power revoked"); IERC721 contractERC721 = IERC721(contractAddress); contractERC721.transferFrom(address(this), to, tokenId); } // *** Wrapping / Unwrapping / Depositing / Withdrawing Le Anime OE to Souls function wrapTokenBatch(uint256[] calldata tokenId) public { //address mainOwner; for (uint256 i = 0; i < tokenId.length ; i++){ require(tokenId[i] <= 1573, "Wrapping not existing token "); //user need to set approval on the mainContract to this contract to allow the next transfer to work mainToken.transferFrom(msg.sender, address(this), tokenId[i] + OFFSETNG); //generating the soul & free spirits the first time it gets wrapped if(!_exists(tokenId[i] + OFFSETAN2)) { _mint(msg.sender, tokenId[i] + OFFSETAN2); _mint(msg.sender, tokenId[i] + OFFSET_SPIRITS + OFFSETAN2); } else { _safeTransfer(address(this), msg.sender, tokenId[i] + OFFSETAN2, ""); } } } function unwrapTokenBatch(uint256[] calldata tokenId) public { for (uint256 i = 0; i < tokenId.length ; i++){ transferFrom(msg.sender, address(this), tokenId[i] + OFFSETAN2); mainToken.safeTransferFrom(address(this), msg.sender, tokenId[i] + OFFSETNG); //resets the uriSelection to default uriSelection[tokenId[i] + OFFSETAN2] = false; } } //this is to batch transfer multiple tokens - useful to batch deposit in the merge contract! function transferFromBatch(address from, address to, uint256[] calldata tokenId) public { for (uint256 i = 0; i < tokenId.length ; i++){ transferFrom(from, to, tokenId[i]); } } function transferFromBatchMerger(address from, address to, uint16[] calldata tokenId) public { require(msg.sender == mergeContract, "Not allowed"); for (uint256 i = 0; i < tokenId.length ; i++){ transferFrom(from, to, tokenId[i] + OFFSETAN2); } } //to check if token exists - needed in merge function exists(uint256 tokenId) public view returns (bool) { return _exists(tokenId); } // *** Hero Section to mint/burn the hero ID from the main contract address function mintHero(uint256 heroId, address account) external { require(msg.sender == mergeContract, "Not allowed"); require(mergeActive, "Merge not active"); require(heroId <= OFFSETAN2, "Only for Heroes"); _mint(account, heroId); } function burnHero(uint256 heroId) external { require(msg.sender == mergeContract, "Not allowed"); require(mergeActive, "Merge not active"); require(heroId <= OFFSETAN2, "Only for Heroes"); _burn(heroId); } // *** Minting Section Souls/Spirits*** function mintSpirits(address account, uint256[] calldata tokenId) external { require(msg.sender == minterContract); for (uint256 i = 0; i < tokenId.length ; i++){ require(tokenId[i] >= spiritsFirst && tokenId[i] <= spiritsLast, "Out of Bound minting"); _mint(account, tokenId[i] + OFFSETAN2); } } // *** Royalty standard - EIP-2981 *** function setRoyaltyPercentageBasisPoints(uint256 royaltyPercentageBasisPoints) public onlyOwner { _royaltyBps = royaltyPercentageBasisPoints; } function setRoyaltyReceipientAddress(address payable royaltyReceipientAddress) public onlyOwner { _royaltyRecipient = royaltyReceipientAddress; } function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = (salePrice * _royaltyBps) / 10000; return (_royaltyRecipient, royalty); } }
this is to batch transfer multiple tokens - useful to batch deposit in the merge contract!
function transferFromBatch(address from, address to, uint256[] calldata tokenId) public { for (uint256 i = 0; i < tokenId.length ; i++){ transferFrom(from, to, tokenId[i]); } }
7,685,200
/** *Submitted for verification at Etherscan.io on 2020-11-08 */ interface PermittedAddressesInterface { function permittedAddresses(address _address) external view returns(bool); function addressesTypes(address _address) external view returns(string memory); function isMatchTypes(address _address, uint256 addressType) external view returns(bool); } interface SmartFundERC20LightFactoryInterface { function createSmartFundLight( address _owner, string memory _name, uint256 _successFee, address _exchangePortalAddress, address _permittedAddresses, address _coinAddress, address _fundValueOracle, bool _isRequireTradeVerification, address _cotraderGlobalConfig ) external returns(address); } interface SmartFundETHLightFactoryInterface { function createSmartFundLight( address _owner, string memory _name, uint256 _successFee, address _exchangePortalAddress, address _permittedAddresses, address _fundValueOracle, bool _isRequireTradeVerification, address _cotraderGlobalConfig ) external returns(address); } interface SmartFundERC20FactoryInterface { function createSmartFund( address _owner, string memory _name, uint256 _successFee, address _exchangePortalAddress, address _poolPortalAddress, address _defiPortal, address _permittedAddresses, address _coinAddress, address _fundValueOracle, bool _isRequireTradeVerification, address _cotraderGlobalConfig ) external returns(address); } interface SmartFundETHFactoryInterface { function createSmartFund( address _owner, string memory _name, uint256 _successFee, address _exchangePortalAddress, address _poolPortalAddress, address _defiPortal, address _permittedAddresses, address _fundValueOracle, bool _isRequireTradeVerification, address _cotraderGlobalConfig ) external returns(address); } pragma solidity ^0.6.12; /* * @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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } /** * @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. */ 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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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); } /* * The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts */ contract SmartFundRegistry is Ownable { address[] public smartFunds; // The Smart Contract which stores the addresses of all the authorized address PermittedAddressesInterface public permittedAddresses; // Addresses of portals address public poolPortalAddress; address public exchangePortalAddress; address public defiPortalAddress; // Default maximum success fee is 3000/30% uint256 public maximumSuccessFee = 3000; // Address of stable coin can be set in constructor and changed via function address public stableCoinAddress; // Address of CoTrader coin be set in constructor address public COTCoinAddress; // Address of Oracle address public oracleAddress; // Address of Cotrader global config address public cotraderGlobalConfig; // Factories SmartFundETHFactoryInterface public smartFundETHFactory; SmartFundERC20FactoryInterface public smartFundERC20Factory; SmartFundETHLightFactoryInterface public smartFundETHLightFactory; SmartFundERC20LightFactoryInterface public smartFundERC20LightFactory; // Enum for detect fund type in create fund function // NOTE: You can add a new type at the end, but do not change this order enum FundType { ETH, USD, COT } event SmartFundAdded(address indexed smartFundAddress, address indexed owner); /** * @dev contructor * * @param _exchangePortalAddress Address of the initial ExchangePortal contract * @param _poolPortalAddress Address of the initial PoolPortal contract * @param _stableCoinAddress Address of the stable coin * @param _COTCoinAddress Address of Cotrader coin * @param _smartFundETHFactory Address of smartFund ETH factory * @param _smartFundERC20Factory Address of smartFund USD factory * @param _smartFundETHLightFactory Address of smartFund ETH factory * @param _smartFundERC20LightFactory Address of smartFund USD factory * @param _defiPortalAddress Address of defiPortal contract * @param _permittedAddresses Address of permittedAddresses contract * @param _oracleAddress Address of fund value oracle contract * @param _cotraderGlobalConfig Address of CoTraderGlobalConfig contract */ constructor( address _exchangePortalAddress, address _poolPortalAddress, address _stableCoinAddress, address _COTCoinAddress, address _smartFundETHFactory, address _smartFundERC20Factory, address _smartFundETHLightFactory, address _smartFundERC20LightFactory, address _defiPortalAddress, address _permittedAddresses, address _oracleAddress, address _cotraderGlobalConfig ) public { exchangePortalAddress = _exchangePortalAddress; poolPortalAddress = _poolPortalAddress; stableCoinAddress = _stableCoinAddress; COTCoinAddress = _COTCoinAddress; smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory); smartFundERC20Factory = SmartFundERC20FactoryInterface(_smartFundERC20Factory); smartFundETHLightFactory = SmartFundETHLightFactoryInterface(_smartFundETHLightFactory); smartFundERC20LightFactory = SmartFundERC20LightFactoryInterface(_smartFundERC20LightFactory); defiPortalAddress = _defiPortalAddress; permittedAddresses = PermittedAddressesInterface(_permittedAddresses); oracleAddress = _oracleAddress; cotraderGlobalConfig = _cotraderGlobalConfig; } /** * @dev Creates a new Full SmartFund * * @param _name The name of the new fund * @param _successFee The fund managers success fee * @param _fundType Fund type enum number * @param _isRequireTradeVerification If true fund can buy only tokens, * which include in Merkle Three white list */ function createSmartFund( string memory _name, uint256 _successFee, uint256 _fundType, bool _isRequireTradeVerification ) public { // Require that the funds success fee be less than the maximum allowed amount require(_successFee <= maximumSuccessFee); address smartFund; // ETH case if(block.number == uint256(FundType.ETH)){ //injected CONTRACT AFFECTED BY MINERS // Create ETH Fund smartFund = smartFundETHFactory.createSmartFund( msg.sender, _name, _successFee, // manager and platform fee exchangePortalAddress, poolPortalAddress, defiPortalAddress, address(permittedAddresses), oracleAddress, _isRequireTradeVerification, cotraderGlobalConfig ); } // ERC20 case else{ address coinAddress = getERC20AddressByFundType(_fundType); // Create ERC20 based fund smartFund = smartFundERC20Factory.createSmartFund( msg.sender, _name, _successFee, // manager and platform fee exchangePortalAddress, poolPortalAddress, defiPortalAddress, address(permittedAddresses), coinAddress, oracleAddress, _isRequireTradeVerification, cotraderGlobalConfig ); } smartFunds.push(smartFund); emit SmartFundAdded(smartFund, msg.sender); } /** * @dev Creates a new Light SmartFund * * @param _name The name of the new fund * @param _successFee The fund managers success fee * @param _fundType Fund type enum number * @param _isRequireTradeVerification If true fund can buy only tokens, * which include in Merkle Three white list */ function createSmartFundLight( string memory _name, uint256 _successFee, uint256 _fundType, bool _isRequireTradeVerification ) public { // Require that the funds success fee be less than the maximum allowed amount require(_successFee <= maximumSuccessFee); address smartFund; // ETH case if(block.timestamp == uint256(FundType.ETH)){ //injected CONTRACT AFFECTED BY MINERS // Create ETH Fund smartFund = smartFundETHLightFactory.createSmartFundLight( msg.sender, _name, _successFee, // manager and platform fee exchangePortalAddress, address(permittedAddresses), oracleAddress, _isRequireTradeVerification, cotraderGlobalConfig ); } // ERC20 case else{ address coinAddress = getERC20AddressByFundType(_fundType); // Create ERC20 based fund smartFund = smartFundERC20LightFactory.createSmartFundLight( msg.sender, _name, _successFee, // manager and platform fee exchangePortalAddress, address(permittedAddresses), coinAddress, oracleAddress, _isRequireTradeVerification, cotraderGlobalConfig ); } smartFunds.push(smartFund); emit SmartFundAdded(smartFund, msg.sender); } function getERC20AddressByFundType(uint256 _fundType) private view returns(address coinAddress){ // Define coin address dependse of fund type coinAddress = _fundType == uint256(FundType.USD) ? stableCoinAddress : COTCoinAddress; } function totalSmartFunds() public view returns (uint256) { return smartFunds.length; } function getAllSmartFundAddresses() public view returns(address[] memory) { address[] memory addresses = new address[](smartFunds.length); for (uint i; i < smartFunds.length; i++) { addresses[i] = address(smartFunds[i]); } return addresses; } /** * @dev Owner can set a new default ExchangePortal address * * @param _newExchangePortalAddress Address of the new exchange portal to be set */ function setExchangePortalAddress(address _newExchangePortalAddress) external onlyOwner { // Require that the new exchange portal is permitted by permittedAddresses require(permittedAddresses.permittedAddresses(_newExchangePortalAddress)); exchangePortalAddress = _newExchangePortalAddress; } /** * @dev Owner can set a new default Portal Portal address * * @param _poolPortalAddress Address of the new pool portal to be set */ function setPoolPortalAddress(address _poolPortalAddress) external onlyOwner { // Require that the new pool portal is permitted by permittedAddresses require(permittedAddresses.permittedAddresses(_poolPortalAddress)); poolPortalAddress = _poolPortalAddress; } /** * @dev Allows the fund manager to connect to a new permitted defi portal * * @param _newDefiPortalAddress The address of the new permitted defi portal to use */ function setDefiPortal(address _newDefiPortalAddress) public onlyOwner { // Require that the new defi portal is permitted by permittedAddresses require(permittedAddresses.permittedAddresses(_newDefiPortalAddress)); defiPortalAddress = _newDefiPortalAddress; } /** * @dev Owner can set maximum success fee for all newly created SmartFunds * * @param _maximumSuccessFee New maximum success fee */ function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner { maximumSuccessFee = _maximumSuccessFee; } /** * @dev Owner can set new stableCoinAddress * * @param _stableCoinAddress New stable address */ function setStableCoinAddress(address _stableCoinAddress) external onlyOwner { require(permittedAddresses.permittedAddresses(_stableCoinAddress)); stableCoinAddress = _stableCoinAddress; } /** * @dev Owner can set new smartFundETHFactory * * @param _smartFundETHFactory address of ETH factory contract */ function setNewSmartFundETHFactory(address _smartFundETHFactory) external onlyOwner { smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory); } /** * @dev Owner can set new smartFundERC20Factory * * @param _smartFundERC20Factory address of ERC20 factory contract */ function setNewSmartFundERC20Factory(address _smartFundERC20Factory) external onlyOwner { smartFundERC20Factory = SmartFundERC20FactoryInterface(_smartFundERC20Factory); } /** * @dev Owner can set new smartFundETHLightFactory * * @param _smartFundETHLightFactory address of ETH factory contract */ function setNewSmartFundETHLightFactory(address _smartFundETHLightFactory) external onlyOwner { smartFundETHLightFactory = SmartFundETHLightFactoryInterface(_smartFundETHLightFactory); } /** * @dev Owner can set new smartFundERC20LightFactory * * @param _smartFundERC20LightFactory address of ERC20 factory contract */ function setNewSmartFundERC20LightFactory(address _smartFundERC20LightFactory) external onlyOwner { smartFundERC20LightFactory = SmartFundERC20LightFactoryInterface(_smartFundERC20LightFactory); } /** * @dev Owner can set new Oracle * * @param _oracleAddress address of Oracle contract */ function setNewOracle(address _oracleAddress) external onlyOwner { oracleAddress = _oracleAddress; } /** * @dev Allows withdarw tokens from this contract if someone will accidentally send tokens here * * @param _tokenAddress Address of the token to be withdrawn */ function withdrawTokens(address _tokenAddress) external onlyOwner { IERC20 token = IERC20(_tokenAddress); token.transfer(owner(), token.balanceOf(address(this))); } /** * @dev Allows withdarw ETH from this contract if someone will accidentally send tokens here */ function withdrawEther() external onlyOwner { payable(owner()).transfer(address(this).balance); } // Fallback payable function in order to receive ether when fund manager withdraws their cut fallback() external payable {} }
Define coin address dependse of fund type
function getERC20AddressByFundType(uint256 _fundType) private view returns(address coinAddress){ coinAddress = _fundType == uint256(FundType.USD) ? stableCoinAddress : COTCoinAddress; }
7,325,906
./full_match/5/0x94f107C0f8a9effb35332aEA8D11aa405439300d/sources/contracts/messagePassingBridge/LZHandlerUpgradeable.sol
override lzReceive for simpler trustedRemote handling lzReceive must be called by the endpoint for security if will still block the message pathway from (srcChainId, srcAddress). should not receive message from untrusted remote.
function lzReceive( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) public virtual override { if (_msgSender() != address(lzEndpoint)) revert INVALID_ENDPOINT(_msgSender()); if ( _srcAddress.length != trustedRemote.length || trustedRemote.length == 0 || keccak256(_srcAddress) != keccak256(trustedRemote) ) revert INVALID_SENDER(_srcAddress); _blockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload); }
7,039,585
/** *Submitted for verification at Etherscan.io on 2021-10-25 */ // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 rateLimit; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IERC3156FlashBorrower 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); } // Part: IUniswapAnchoredView interface IUniswapAnchoredView { function price(string memory) external returns (uint256); } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: IUniswapV3SwapCallback /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // Part: InterestRateModel interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @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" ); } /** * @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" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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 ); } // Part: OpenZeppelin/[email protected]/Math /** * @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, so we distribute return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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) { 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; } } // Part: iearn-finance/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: CTokenI interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest( uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows ); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow( address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor( uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa ); /** * @notice Event emitted when the reserves are added */ event ReservesAdded( address benefactor, uint256 addAmount, uint256 newTotalReserves ); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced( address admin, uint256 reduceAmount, uint256 newTotalReserves ); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval( address indexed owner, address indexed spender, uint256 amount ); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // Part: IERC20Extended interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); } // Part: IERC3156FlashLender interface IERC3156FlashLender { /** * @dev The amount of currency available to be lent. * @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); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // Part: IUniswapV3Router /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3Router is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _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 // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function apiVersion() external view returns (string memory); function withdraw(uint256 shares, address recipient) external; function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); } // Part: CErc20I interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); function comptroller() external view returns (address); } // Part: ComptrollerI interface ComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, CTokenI[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); // will be deprecated function compSupplySpeeds(address ctoken) external view returns (uint256); function compBorrowSpeeds(address ctoken) external view returns (uint256); function oracle() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.0"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding ); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require( msg.sender == strategist || msg.sender == governance(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyGovernance { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyGovernance { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. Any distributed rewards will cease flowing * to the old address and begin flowing to this address once the change * is in effect. * * This may only be called by the strategist. * @param _rewards The address to use for collecting rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); rewards = _rewards; emit UpdatedRewards(_rewards); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_amountFreed + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * `Harvest()` calls this function after shares are created during * `vault.report()`. You can customize this function to any share * distribution mechanism you want. * * See `vault.report()` for further details. */ function distributeRewards() internal virtual { // Transfer 100% of newly-minted shares awarded to this contract to the rewards address. uint256 balance = vault.balanceOf(address(this)); if (balance > 0) { vault.transfer(rewards, balance); } } /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public view virtual returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition( totalAssets > debtOutstanding ? totalAssets : debtOutstanding ); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Distribute any reward shares earned by the strategy on this report distributeRewards(); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require( HealthCheck(healthCheck).check( profit, loss, debtPayment, debtOutstanding, totalDebt ), "!healthcheck" ); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amount` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.transfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.transfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).transfer( governance(), IERC20(_token).balanceOf(address(this)) ); } } // Part: FlashMintLib library FlashMintLib { using SafeMath for uint256; event Leverage( uint256 amountRequested, uint256 requiredDAI, bool deficit, address flashLoan ); uint256 private constant PRICE_DECIMALS = 1e6; uint256 private constant DAI_DECIMALS = 1e18; uint256 private constant COLLAT_DECIMALS = 1e18; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant CDAI = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; ComptrollerI private constant COMPTROLLER = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant LENDER = 0x1EB4CF3A948E7D72A198fe073cCb8C7a948cD853; bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); function doFlashMint( bool deficit, uint256 amountDesired, address want, uint256 collatRatioDAI ) public returns (uint256) { if (amountDesired == 0) { return 0; } // calculate amount of DAI we need (uint256 requiredDAI, uint256 amountWant) = getFlashLoanParams( want, amountDesired, collatRatioDAI ); bytes memory data = abi.encode(deficit, amountWant); uint256 _fee = IERC3156FlashLender(LENDER).flashFee(DAI, amountWant); // Check that fees have not been increased without us knowing require(_fee == 0); uint256 _allowance = IERC20(DAI).allowance( address(this), address(LENDER) ); if (_allowance < requiredDAI) { IERC20(DAI).approve(address(LENDER), 0); IERC20(DAI).approve(address(LENDER), type(uint256).max); } IERC3156FlashLender(LENDER).flashLoan( IERC3156FlashBorrower(address(this)), DAI, requiredDAI, data ); emit Leverage(amountDesired, requiredDAI, deficit, address(LENDER)); return amountWant; } function maxLiquidity() public view returns (uint256) { return IERC3156FlashLender(LENDER).maxFlashLoan(DAI); } function getFlashLoanParams( address want, uint256 amountDesired, uint256 collatRatioDAI ) internal returns (uint256 requiredDAI, uint256 amountWant) { uint256 priceDAIWant; uint256 decimalsDifference; (priceDAIWant, decimalsDifference, requiredDAI) = getPriceDAIWant( want, amountDesired, collatRatioDAI ); amountWant = amountDesired; // If the cap for flashminting is reduced, we may hit maximum. To avoid reverts in that case we handle the edge case uint256 _maxFlashLoan = maxLiquidity(); if (requiredDAI > _maxFlashLoan) { requiredDAI = _maxFlashLoan.mul(9800).div(10_000); // use 98% of total liquidity available if (address(want) == address(DAI)) { amountWant = requiredDAI; } else { amountWant = requiredDAI .mul(collatRatioDAI) .mul(PRICE_DECIMALS) .div(priceDAIWant) .div(COLLAT_DECIMALS) .div(decimalsDifference); } } } function getPriceDAIWant( address want, uint256 amountDesired, uint256 collatRatioDAI ) internal returns ( uint256 priceDAIWant, uint256 decimalsDifference, uint256 requiredDAI ) { if (want == DAI) { requiredDAI = amountDesired; priceDAIWant = PRICE_DECIMALS; // 1:1 decimalsDifference = 1; // 10 ** 0 } else { // NOTE: want decimals need to be <= 18. otherwise this will break uint256 wantDecimals = 10**uint256(IERC20Extended(want).decimals()); decimalsDifference = DAI_DECIMALS.div(wantDecimals); priceDAIWant = getOraclePrice(DAI).mul(PRICE_DECIMALS).div( getOraclePrice(want) ); // requiredDAI = desiredWantInDAI / COLLAT_RATIO_DAI // desiredWantInDAI = (desiredWant / priceDAIWant) // NOTE: decimals need adjustment (e.g. BTC: 8 / ETH: 18) requiredDAI = amountDesired .mul(PRICE_DECIMALS) .mul(COLLAT_DECIMALS) .mul(decimalsDifference) .div(priceDAIWant) .div(collatRatioDAI); } } function getOraclePrice(address token) internal returns (uint256) { string memory symbol; // Symbol for WBTC is BTC in oracle if (token == WBTC) { symbol = "BTC"; } else if (token == WETH) { symbol = "ETH"; } else { symbol = IERC20Extended(token).symbol(); } IUniswapAnchoredView oracle = IUniswapAnchoredView( COMPTROLLER.oracle() ); return oracle.price(symbol); } function loanLogic( bool deficit, uint256 amountDAI, uint256 amount, CErc20I cToken ) public returns (bytes32) { // if want is not DAI, we provide flashminted DAI to borrow want and be able to lever up/down // if want is DAI, we use it directly to lever up/down bool isDai; // We check if cToken is DAI to save a couple of unnecessary calls if (address(cToken) == address(CDAI)) { isDai = true; require(amountDAI == amount, "!amounts"); } uint256 daiBal = IERC20(DAI).balanceOf(address(this)); if (deficit) { if (!isDai) { require(CErc20I(CDAI).mint(daiBal) == 0, "!mint_flash"); require(cToken.redeemUnderlying(amount) == 0, "!redeem_down"); } //if in deficit we repay amount and then withdraw uint256 repayAmount = Math.min( IERC20(cToken.underlying()).balanceOf(address(this)), cToken.borrowBalanceCurrent(address(this)) ); require(cToken.repayBorrow(repayAmount) == 0, "!repay_down"); require(CErc20I(CDAI).redeemUnderlying(amountDAI) == 0, "!redeem"); } else { // if levering up borrow and deposit require(CErc20I(CDAI).mint(daiBal) == 0, "!mint_flash"); require(cToken.borrow(amount) == 0, "!borrow_up"); if (!isDai) { require( cToken.mint( IERC20(cToken.underlying()).balanceOf(address(this)) ) == 0, "!mint_up" ); require( CErc20I(CDAI).redeemUnderlying(amountDAI) == 0, "!redeem" ); } } return CALLBACK_SUCCESS; } } // File: Strategy.sol contract Strategy is BaseStrategy, IERC3156FlashBorrower { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used event Leverage( uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan ); // Comptroller address for compound.finance ComptrollerI private constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //Only three tokens we use address private constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; CErc20I public cToken; bool public useUniV3; // fee pool to use in UniV3 in basis points(default: 0.3% = 3000) uint24 public compToWethSwapFee; uint24 public wethToWantSwapFee; IUniswapV2Router02 public currentV2Router; IUniswapV2Router02 private constant UNI_V2_ROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Router02 private constant SUSHI_V2_ROUTER = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); IUniswapV3Router private constant UNI_V3_ROUTER = IUniswapV3Router(0xE592427A0AEce92De3Edee1F18E0157C05861564); uint256 public collatRatioDAI; uint256 public collateralTarget; // total borrow / total supply ratio we are targeting (100% = 1e18) uint256 private blocksToLiquidationDangerZone; // minimum number of blocks before liquidation uint256 public minWant; // minimum amount of want to act on // Rewards handling bool public dontClaimComp; // enable/disables COMP claiming uint256 public minCompToSell; // minimum amount of COMP to be sold bool public flashMintActive; // To deactivate flash loan provider if needed bool public forceMigrate; bool public fourThreeProtection; constructor(address _vault, address _cToken) public BaseStrategy(_vault) { _initializeThis(_cToken); } function approveTokenMax(address token, address spender) internal { IERC20(token).safeApprove(spender, type(uint256).max); } function name() external view override returns (string memory) { return "GenLevCompV3"; } function _initializeThis(address _cToken) internal { cToken = CErc20I(address(_cToken)); require(IERC20Extended(address(want)).decimals() <= 18); // dev: want not supported currentV2Router = SUSHI_V2_ROUTER; //pre-set approvals approveTokenMax(comp, address(UNI_V2_ROUTER)); approveTokenMax(comp, address(SUSHI_V2_ROUTER)); approveTokenMax(comp, address(UNI_V3_ROUTER)); approveTokenMax(address(want), address(cToken)); approveTokenMax(FlashMintLib.DAI, address(FlashMintLib.LENDER)); // Enter Compound's DAI market to take it into account when using flashminted DAI as collateral address[] memory markets; if (address(cToken) != address(FlashMintLib.CDAI)) { markets = new address[](2); markets[0] = address(FlashMintLib.CDAI); markets[1] = address(cToken); // Only approve this if want != DAI, otherwise will fail approveTokenMax(FlashMintLib.DAI, address(FlashMintLib.CDAI)); } else { markets = new address[](1); markets[0] = address(FlashMintLib.CDAI); } compound.enterMarkets(markets); //comp speed is amount to borrow or deposit (so half the total distribution for want) compToWethSwapFee = 3000; wethToWantSwapFee = 3000; // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 100; // multiple before triggering harvest debtThreshold = 1e30; // set minWant to 1e-5 want minWant = uint256( uint256(10)**uint256((IERC20Extended(address(want))).decimals()) ).div(1e5); minCompToSell = 0.1 ether; collateralTarget = 0.73 ether; collatRatioDAI = 0.73 ether; blocksToLiquidationDangerZone = 46500; flashMintActive = true; } /* * Control Functions */ function setFourThreeProtection(bool _fourThreeProtection) external management { fourThreeProtection = _fourThreeProtection; } function setUniV3PathFees( uint24 _compToWethSwapFee, uint24 _wethToWantSwapFee ) external management { compToWethSwapFee = _compToWethSwapFee; wethToWantSwapFee = _wethToWantSwapFee; } function setDontClaimComp(bool _dontClaimComp) external management { dontClaimComp = _dontClaimComp; } function setUseUniV3(bool _useUniV3) external management { useUniV3 = _useUniV3; } function setToggleV2Router() external management { currentV2Router = currentV2Router == SUSHI_V2_ROUTER ? UNI_V2_ROUTER : SUSHI_V2_ROUTER; } function setFlashMintActive(bool _flashMintActive) external management { flashMintActive = _flashMintActive; } function setForceMigrate(bool _force) external onlyGovernance { forceMigrate = _force; } function setMinCompToSell(uint256 _minCompToSell) external management { minCompToSell = _minCompToSell; } function setMinWant(uint256 _minWant) external management { minWant = _minWant; } function setCollateralTarget(uint256 _collateralTarget) external management { (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); require(collateralFactorMantissa > _collateralTarget); collateralTarget = _collateralTarget; } function setCollatRatioDAI(uint256 _collatRatioDAI) external management { collatRatioDAI = _collatRatioDAI; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public view override returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = balanceOfToken(comp); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck( comp, address(want), _claimableComp.add(currentComp) ); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return balanceOfToken(address(want)) .add(deposits) .add(conservativeWant) .sub(borrows); } function balanceOfToken(address token) internal view returns (uint256) { return IERC20(token).balanceOf(address(this)); } //predicts our profit at next report function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets.sub(debt); } } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public view override returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone; } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck( address start, address end, uint256 _amount ) public view returns (uint256) { if (_amount == 0) { return 0; } uint256[] memory amounts = currentV2Router.getAmountsOut( _amount, getTokenOutPathV2(start, end) ); return amounts[amounts.length - 1]; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit1 = deposits .mul(collateralFactorMantissa) .div(1e18); uint256 collateralisedDeposit = collateralisedDeposit1; uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return type(uint256).max; } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1.sub(denom2); //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } uint256 distributionPerBlockSupply = compound.compSupplySpeeds( address(cToken) ); uint256 distributionPerBlockBorrow = compound.compBorrowSpeeds( address(cToken) ); uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken .mul(cToken.exchangeRateStored()) .div(1e18); uint256 blockShareSupply = 0; if (totalSupply > 0) { blockShareSupply = deposits.mul(distributionPerBlockSupply).div( totalSupply ); } uint256 blockShareBorrow = 0; if (totalBorrow > 0) { blockShareBorrow = borrows.mul(distributionPerBlockBorrow).div( totalBorrow ); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast = (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare); } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { ( , uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate ) = cToken.getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() public returns (uint256 deposits, uint256 borrows) { deposits = cToken.balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = cToken.borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; // for clarity. also reduces bytesize if (balanceOfToken(address(cToken)) == 0) { uint256 wantBalance = balanceOfToken(address(want)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = balanceOfToken(address(want)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; //Balance - Total Debt is profit if (balance > debt) { _profit = balance.sub(debt); if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)) { _debtPayment = _debtOutstanding; } else { _debtPayment = wantBalance.sub(_profit); } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt.sub(balance); _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = balanceOfToken(address(want)); if (_wantBal < _debtOutstanding) { //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if (balanceOfToken(address(cToken)) > 1) { _withdrawSome(_debtOutstanding.sub(_wantBal)); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition( _wantBal.sub(_debtOutstanding), true ); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation if (position > minWant) { //if flashloan is not active we just try our best with basic leverage if (!flashMintActive) { uint256 i = 0; while (position > 0) { position = position.sub(_noFlashLoan(position, deficit)); if (i >= 6) { break; } i++; } } else { //if there is huge position to improve we want to do normal leverage. it is quicker if (position > FlashMintLib.maxLiquidity()) { position = position.sub(_noFlashLoan(position, deficit)); } //flash loan to position if (position > minWant) { doFlashMint(deficit, position); } } } } /************* * Very important function * Input: amount we want to withdraw and whether we are happy to pay extra for Aave. * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition( _amount, false ); //If there is no deficit we dont need to adjust position //if the position change is tiny do nothing if (deficit && position > minWant) { //we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans if (flashMintActive) { position = position.sub(doFlashMint(deficit, position)); } uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > minWant.add(100)) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= 5) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 tempColla = collateralTarget; uint256 reservedAmount = 0; if (tempColla == 0) { tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = borrowBalance.mul(1e18).div(tempColla); if (depositBalance >= reservedAmount) { uint256 redeemable = depositBalance.sub(reservedAmount); uint256 balan = cToken.balanceOf(address(this)); if (balan > 1) { if (redeemable < _amount) { cToken.redeemUnderlying(redeemable); } else { cToken.redeemUnderlying(_amount); } } } if ( collateralTarget == 0 && balanceOfToken(address(want)) > borrowBalance ) { cToken.repayBorrow(borrowBalance); } } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if (balance > unwoundDeposit) { balance = unwoundDeposit; } desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow.sub(1e5); } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows.sub(desiredBorrow); //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow.sub(borrows); } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = balanceOfToken(address(want)); uint256 assets = netBalanceLent().add(_balance); uint256 debtOutstanding = vault.debtOutstanding(); if (debtOutstanding > assets) { _loss = debtOutstanding.sub(assets); } (uint256 deposits, uint256 borrows) = getLivePosition(); if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can //1 token causes rounding error with withdrawUnderlying if (balanceOfToken(address(cToken)) > 1) { _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min( _amountNeeded, balanceOfToken(address(want)) ); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min( _amountNeeded, balanceOfToken(address(want)) ); } else { _amountFreed = _amountNeeded; } } // To prevent the vault from moving on to the next strategy in the queue // when we return the amountRequested minus dust, take a dust sized loss if (_amountFreed < _amountNeeded) { uint256 diff = _amountNeeded.sub(_amountFreed); if (diff <= minWant) { _loss = diff; } } if (fourThreeProtection) { require(_amountNeeded == _amountFreed.add(_loss)); // dev: fourThreeProtection } } function _claimComp() internal { if (dontClaimComp) { return; } CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cToken; compound.claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = balanceOfToken(comp); if (_comp < minCompToSell) { return; } if (useUniV3) { UNI_V3_ROUTER.exactInput( IUniswapV3Router.ExactInputParams( getTokenOutPathV3(comp, address(want)), address(this), now, _comp, 0 ) ); } else { currentV2Router.swapExactTokensForTokens( _comp, 0, getTokenOutPathV2(comp, address(want)), address(this), now ); } } function getTokenOutPathV2(address _tokenIn, address _tokenOut) internal pure returns (address[] memory _path) { bool isWeth = _tokenIn == address(weth) || _tokenOut == address(weth); _path = new address[](isWeth ? 2 : 3); _path[0] = _tokenIn; if (isWeth) { _path[1] = _tokenOut; } else { _path[1] = address(weth); _path[2] = _tokenOut; } } function getTokenOutPathV3(address _tokenIn, address _tokenOut) internal view returns (bytes memory _path) { if (address(want) == weth) { _path = abi.encodePacked( address(_tokenIn), compToWethSwapFee, address(weth) ); } else { _path = abi.encodePacked( address(_tokenIn), compToWethSwapFee, address(weth), wethToWantSwapFee, address(_tokenOut) ); } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { if (!forceMigrate) { (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot( address(this) ); require(borrowBalance < 10_000); IERC20 _comp = IERC20(comp); uint256 _compB = balanceOfToken(address(_comp)); if (_compB > 0) { _comp.safeTransfer(_newStrategy, _compB); } } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); if (deficit) { amount = _normalDeleverage( max, lent, borrowed, collateralFactorMantissa ); } else { amount = _normalLeverage( max, lent, borrowed, collateralFactorMantissa ); } emit Leverage(max, amount, deficit, address(0)); } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if (collatRatio != 0) { theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cToken.exchangeRateStored(); //redeemTokens = redeemAmountIn * 1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if ( deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10 ) { deleveragedAmount = deleveragedAmount.sub(uint256(10)); cToken.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cToken.repayBorrow(deleveragedAmount); } } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } if (leveragedAmount > 10) { leveragedAmount = leveragedAmount.sub(uint256(10)); cToken.borrow(leveragedAmount); cToken.mint(balanceOfToken(address(want))); } } //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external management { require(cToken.redeemUnderlying(amount) == 0); require(cToken.repayBorrow(amount) == 0); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyGovernance { require(cToken.redeemUnderlying(amount) == 0); // dev: !manual-release-want } function protectedTokens() internal view override returns (address[] memory) {} /****************** * Flash mint stuff ****************/ // Flash loan // amount desired is how much we are willing for position to change function doFlashMint(bool deficit, uint256 amountDesired) internal returns (uint256) { return FlashMintLib.doFlashMint( deficit, amountDesired, address(want), collatRatioDAI ); } //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external override returns (bytes32) { require(msg.sender == FlashMintLib.LENDER); require(initiator == address(this)); (bool deficit, uint256 amountWant) = abi.decode(data, (bool, uint256)); return FlashMintLib.loanLogic(deficit, amount, amountWant, cToken); } // -- Internal Helper functions -- // function mgtm_check() internal view { require( msg.sender == governance() || msg.sender == strategist, "!authorized" ); } modifier management() { mgtm_check(); _; } }
NOTE: want decimals need to be <= 18. otherwise this will break requiredDAI = desiredWantInDAI / COLLAT_RATIO_DAI desiredWantInDAI = (desiredWant / priceDAIWant) NOTE: decimals need adjustment (e.g. BTC: 8 / ETH: 18)
function getPriceDAIWant( address want, uint256 amountDesired, uint256 collatRatioDAI ) internal returns ( uint256 priceDAIWant, uint256 decimalsDifference, uint256 requiredDAI ) { if (want == DAI) { requiredDAI = amountDesired; uint256 wantDecimals = 10**uint256(IERC20Extended(want).decimals()); decimalsDifference = DAI_DECIMALS.div(wantDecimals); priceDAIWant = getOraclePrice(DAI).mul(PRICE_DECIMALS).div( getOraclePrice(want) ); requiredDAI = amountDesired .mul(PRICE_DECIMALS) .mul(COLLAT_DECIMALS) .mul(decimalsDifference) .div(priceDAIWant) .div(collatRatioDAI); } }
1,826,349
./full_match/4/0x293bB1415f6e9f6059641A0611366a798D514270/sources/AirnextToken.sol
Les administrateurs refusent le gros transfert
function refuseTransfer(address _sender, address _recipient) public returns(bool){ Latency storage thisBigTransfers = BigTransfers[_sender][_recipient]; require (thisBigTransfers._amount > 0, 'Ligne de tableau non valide'); require (msg.sender == addressAdminAirnext || msg.sender == addressTokenSale || msg.sender == addressTeam); thisBigTransfers.TransferEvent[msg.sender] = false; if(thisBigTransfers.TransferEvent[addressAdminAirnext] == false && thisBigTransfers.TransferEvent[addressTokenSale] == false || thisBigTransfers.TransferEvent[addressTeam] == false && thisBigTransfers.TransferEvent[addressTokenSale] == false || thisBigTransfers.TransferEvent[addressTeam] == false && thisBigTransfers.TransferEvent[addressAdminAirnext] == false) { thisBigTransfers.completed = false; thisBigTransfers.currState = State.REJECTED; } return false; }
794,021
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; } // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_wrappers, rates); } } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if ((_rates[i] < _rates[minIndex] && _rates[i] > 0) || _rates[minIndex] == 0) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Faucet { function gulp(address) public virtual; } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x71eC9a4fCE561c3936a511D9ebb05B60CF2bA519; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract ManagerLike { function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint wad) public { GemLike(gem).transfer(dst, wad); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } library Address { 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); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); if (originationFee > 0) { ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee); } approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv, uint256 liqRatio, bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]), borrowRateStable: ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]), totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user)); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x11c937fD367D75465DC211c367684d8d4520E6f9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, msg.value, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, msg.value, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(swapedTokens >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _msgValue msg.value in transaction /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _msgValue, uint256 _srcAmount) internal returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return _msgValue; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (_msgValue > _srcAmount) return _msgValue - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return _msgValue; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, _user); } else { dfsFee = getFee(_closeData.daiAmount, _user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); if (maxDebt >= _exchangeData.srcAmount) { boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); if (maxColl >= _exchangeData.srcAmount) { repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount = getBalance(exchangeData.srcAddr); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); // draw coll if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) { uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this)); require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0); } else { require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); } // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { // swap (, destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, destAmount) = _sell(_data); } else { _data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr); destAmount = _data.srcAmount; } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AAVE_BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x11c937fD367D75465DC211c367684d8d4520E6f9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { (, uint sellAmount) = _sell(exchangeData); getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: cAddresses[0], cDebtAddr: cAddresses[1] }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } }
Get marketId from token address Calculate repay amount (_amount + (2 wei)) Approve transfer from
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); }
7,586,183
./partial_match/3/0x1A6C4E31732e747D2C84084dd28Af3B485646c06/sources/ethmax.sol
Invest Function. If no referrer, referrer = 0x0000000000000000000000000000000000000000 PL_Address.call{value: msg.value.mul(PL_SHARE).div(PERCENTS_DIVIDER)}; PL_Address.call.value(msg.value.mul(PL_SHARE).div(PERCENTS_DIVIDER));
function invest(address referrer) public payable { require(msg.value >= INVEST_MIN_AMOUNT); require(success, "Transfer failed."); User storage user = users[msg.sender]; if (user.referrer == address(0) && users[referrer].deposits.length > 0 && referrer != msg.sender) { user.referrer = referrer; } if (user.referrer != address(0)) { address upline = user.referrer; for (uint256 i = 0; i < 3; i++) { if (upline != address(0)) { uint256 amount = msg.value.mul(REFERRAL_PERCENTS[i]).div(PERCENTS_DIVIDER); users[upline].bonus = users[upline].bonus.add(amount); upline = users[upline].referrer; } else break; } } if (user.deposits.length == 0) { user.checkpoint = block.timestamp; totalUsers = totalUsers.add(1); } user.deposits.push(Deposit(msg.value, 0, block.timestamp)); totalInvested = totalInvested.add(msg.value); totalDeposits = totalDeposits.add(1); ethMaxTokensToClaim[msg.sender] = ethMaxTokensToClaim[msg.sender].add(ethMaxTokens); }
5,110,693
./partial_match/1/0xc6CadA314389430d396C7b0C70c6281e99ca7fe8/sources/src/contracts/FraxlendPair.sol
The ```withdrawFees``` function withdraws fees accumulated _shares Number of fTokens to redeem _recipient Address to send the assets return _amountToTransfer Amount of assets sent to recipient Grab some data from state to save gas Take all available if 0 value passed We must calculate this before we subtract from _totalAsset or invoke _burn
function withdrawFees(uint128 _shares, address _recipient) external onlyOwner returns (uint256 _amountToTransfer) { if (_recipient == address(0)) revert InvalidReceiver(); VaultAccount memory _totalAsset = totalAsset; if (_shares == 0) _shares = uint128(balanceOf(address(this))); _amountToTransfer = _totalAsset.toAmount(_shares, true); _approve(address(this), msg.sender, _shares); _redeem(_totalAsset, _amountToTransfer.toUint128(), _shares, _recipient, address(this)); uint256 _collateralAmount = userCollateralBalance[address(this)]; _removeCollateral(_collateralAmount, _recipient, address(this)); emit WithdrawFees(_shares, _recipient, _amountToTransfer, _collateralAmount); }
2,823,028
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: Account library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } // Part: Actions library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } // Part: ICallee /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } // Part: ISoloMargin interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } // Part: IUni interface IUni{ function getAmountsOut( uint256 amountIn, address[] calldata path ) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: InterestRateModel interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @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"); } /** * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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) { 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; } } // Part: iearn-finance/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: CTokenI interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // Part: DydxFlashloanBase contract DydxFlashloanBase { using SafeMath for uint256; function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: CErc20I interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); } // Part: ComptrollerI interface ComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, CTokenI[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol /******************** * * A lender optimisation strategy for any erc20 asset * https://github.com/Grandthrax/yearnV2-generic-lender-strat * v0.4.2 * ********************* */ contract Strategy is BaseStrategy, DydxFlashloanBase, ICallee { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan); //Flash Loan Providers address private constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; // Comptroller address for compound.finance ComptrollerI private constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //Only three tokens we use address private constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; CErc20I public cToken; //address public constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //Operating variables uint256 public collateralTarget = 0.73 ether; // 73% uint256 public blocksToLiquidationDangerZone = 46500; // 7 days = 60*60*24*7/13 uint256 public minWant; // Default is 0. Only lend if we have enough want to be worth it. Can be set to non-zero uint256 public minCompToSell = 0.1 ether; //used both as the threshold to sell but also as a trigger for harvest //To deactivate flash loan provider if needed bool public DyDxActive = true; bool public forceMigrate; // default is false uint256 public dyDxMarketId; constructor(address _vault, address _cToken) public BaseStrategy(_vault) { cToken = CErc20I(address(_cToken)); //pre-set approvals IERC20(comp).safeApprove(uniswapRouter, type(uint256).max); want.safeApprove(address(cToken), type(uint256).max); want.safeApprove(SOLO, type(uint256).max); // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 100; // multiple before triggering harvest _setMarketIdFromTokenAddress(); } function name() external override view returns (string memory){ return "StrategyGenericLevCompFarm"; } /* * Control Functions */ function setDyDx(bool _dydx) external management { DyDxActive = _dydx; } function setForceMigrate(bool _force) external onlyGovernance { forceMigrate = _force; } function setMinCompToSell(uint256 _minCompToSell) external management { minCompToSell = _minCompToSell; } function setMinWant(uint256 _minWant) external management { minWant = _minWant; } function updateMarketId() external management { _setMarketIdFromTokenAddress(); } function setCollateralTarget(uint256 _collateralTarget) external management { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); require(collateralFactorMantissa > _collateralTarget); collateralTarget = _collateralTarget; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public override view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = IERC20(comp).balanceOf(address(this)); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp)); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows); } //predicts our profit at next report function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets - debt; } } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public override view returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone; } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } address[] memory path; if(start == weth){ path = new address[](2); path[0] = weth; path[1] = end; }else{ path = new address[](3); path[0] = start; path[1] = weth; path[2] = end; } uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18); uint256 collateralisedDeposit = collateralisedDeposit1; uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return type(uint256).max; } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1 - denom2; //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } //comp speed is amount to borrow or deposit (so half the total distribution for want) uint256 distributionPerBlock = compound.compSpeeds(address(cToken)); uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18); uint256 blockShareSupply = 0; if(totalSupply > 0){ blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply); } uint256 blockShareBorrow = 0; if(totalBorrow > 0){ blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare); } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { (, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() public returns (uint256 deposits, uint256 borrows) { deposits = cToken.balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = cToken.borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity. also reduces bytesize if (cToken.balanceOf(address(this)) == 0) { uint256 wantBalance = want.balanceOf(address(this)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = want.balanceOf(address(this)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; //Balance - Total Debt is profit if (balance > debt) { _profit = balance - debt; if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)){ _debtPayment = _debtOutstanding; }else{ _debtPayment = wantBalance - _profit; } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt - balance; _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = want.balanceOf(address(this)); if(_wantBal < _debtOutstanding){ //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if(cToken.balanceOf(address(this)) > 1){ _withdrawSome(_debtOutstanding - _wantBal); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation if (position > minWant) { //if dydx is not active we just try our best with basic leverage if (!DyDxActive) { uint i = 0; while(position > 0){ position = position.sub(_noFlashLoan(position, deficit)); if(i >= 6){ break; } i++; } } else { //if there is huge position to improve we want to do normal leverage. it is quicker if (position > want.balanceOf(SOLO)) { position = position.sub(_noFlashLoan(position, deficit)); } //flash loan to position if(position > minWant){ doDyDxFlashLoan(deficit, position); } } } } /************* * Very important function * Input: amount we want to withdraw and whether we are happy to pay extra for Aave. * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false); //If there is no deficit we dont need to adjust position //if the position change is tiny do nothing if (deficit && position > minWant) { //we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans if (DyDxActive) { position = position.sub(doDyDxFlashLoan(deficit, position)); } uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > minWant.add(100)) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= 5) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 tempColla = collateralTarget; uint256 reservedAmount = 0; if(tempColla == 0){ tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = borrowBalance.mul(1e18).div(tempColla); if(depositBalance >= reservedAmount){ uint256 redeemable = depositBalance.sub(reservedAmount); if (redeemable < _amount) { cToken.redeemUnderlying(redeemable); } else { cToken.redeemUnderlying(_amount); } } if(collateralTarget == 0 && want.balanceOf(address(this)) > borrowBalance){ cToken.repayBorrow(borrowBalance); } //let's sell some comp if we have more than needed //flash loan would have sent us comp if we had some accrued so we don't need to call claim comp _disposeOfComp(); } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if(balance > unwoundDeposit) balance = unwoundDeposit; desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow - 1e5; } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows - desiredBorrow; //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow - borrows; } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); uint256 assets = netBalanceLent().add(_balance); uint256 debtOutstanding = vault.debtOutstanding(); if(debtOutstanding > assets){ _loss = debtOutstanding - assets; } if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can (uint256 deposits, uint256 borrows) = getLivePosition(); //1 token causes rounding error with withdrawUnderlying if(cToken.balanceOf(address(this)) > 1){ _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); }else{ _amountFreed = _amountNeeded; } } } function _claimComp() internal { CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cToken; compound.claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { address[] memory path = new address[](3); path[0] = comp; path[1] = weth; path[2] = address(want); IUni(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now); } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { if(!forceMigrate){ (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this)); require(borrowBalance < 10_000); IERC20 _comp = IERC20(comp); uint _compB = _comp.balanceOf(address(this)); if(_compB > 0){ _comp.safeTransfer(_newStrategy, _compB); } } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); if (deficit) { amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa); } else { amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa); } emit Leverage(max, amount, deficit, address(0)); } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if(collatRatio != 0){ theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cToken.exchangeRateStored(); //redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){ deleveragedAmount = deleveragedAmount -10; cToken.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cToken.repayBorrow(deleveragedAmount); } } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } if(leveragedAmount > 10){ leveragedAmount = leveragedAmount -10; cToken.borrow(leveragedAmount); cToken.mint(want.balanceOf(address(this))); } } //called by flash loan function _loanLogic( bool deficit, uint256 amount ) internal { uint256 bal = want.balanceOf(address(this)); require(bal >= amount); // to stop malicious calls //if in deficit we repay amount and then withdraw if (deficit) { cToken.repayBorrow(amount); //if we are withdrawing we take more to cover fee cToken.redeemUnderlying( amount.add(2)); } else { //check if this failed incase we borrow into liquidation require(cToken.mint(bal) == 0); //borrow more to cover fee // fee is so low for dydx that it does not effect our liquidation risk. //DONT USE FOR AAVE cToken.borrow( amount.add(2)); } } //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external management{ require(cToken.redeemUnderlying(amount) == 0); require(cToken.repayBorrow(amount) == 0); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyGovernance{ require(cToken.redeemUnderlying(amount) ==0); } function protectedTokens() internal override view returns (address[] memory) { } /****************** * Flash loan stuff ****************/ // Flash loan DXDY // amount desired is how much we are willing for position to change function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) { if(amountDesired == 0){ return 0; } uint256 amount = amountDesired; ISoloMargin solo = ISoloMargin(SOLO); // Not enough want in DyDx. So we take all we can uint256 amountInSolo = want.balanceOf(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } bytes memory data = abi.encode(deficit, amount); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( // Encode custom data for callFunction data ); operations[2] = _getDepositAction(dyDxMarketId, amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(amountDesired, amount, deficit, SOLO); return amount; } //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } //DyDx calls this function after doing flash loan function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256)); require(msg.sender == SOLO); require(sender == address(this)); _loanLogic(deficit, amount); } // -- Internal Helper functions -- // function _setMarketIdFromTokenAddress() internal { ISoloMargin solo = ISoloMargin(SOLO); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == address(want)) { dyDxMarketId = i; return; } } revert(); } function ethToWant(uint256 _amtInWei) public view override returns (uint256) { return priceCheck(weth, address(want), _amtInWei); } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed,) = liquidatePosition(vault.debtOutstanding()); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 position = deposits.sub(borrows); //we want to revert if we can't liquidateall if(!forceMigrate) { require(position < minWant); } } function mgtm_check() internal { require(msg.sender == governance() || msg.sender == strategist); } modifier management() { mgtm_check(); _; } }
Flash loan DXDY amount desired is how much we are willing for position to change
function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) { if(amountDesired == 0){ return 0; } uint256 amount = amountDesired; ISoloMargin solo = ISoloMargin(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } bytes memory data = abi.encode(deficit, amount); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( ); operations[2] = _getDepositAction(dyDxMarketId, amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(amountDesired, amount, deficit, SOLO); return amount; }
1,254,670
./full_match/1/0x07B0226465A50300F91c8A7930f90aEcae3D6Ed4/sources/contracts/staking/Series.sol
Claim profit share and OGN rewards. return claimedETH - amount of ETH profit share claimed return claimedOGN - amount of OGN rewards claimed/
function claim() external override requireActiveSeason returns (uint256, uint256) { address userAddress = msg.sender; ISeason season = _acquireClaimingSeason(); (uint256 rewardETH, uint256 rewardOGN) = season.claim(userAddress); _transferRewards(userAddress, rewardETH, rewardOGN); return (rewardETH, rewardOGN); }
16,523,429
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. library SafeMath { function ADD750(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "add: +"); return c; } function ADD750(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, errorMessage); return c; } function SUB186(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB186(a, b, "sub: -"); } function SUB186(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL249(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING // 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; } uint c = a * b; require(c / a == b, "mul: *"); return c; } function MUL249(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // 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; } uint c = a * b; require(c / a == b, errorMessage); return c; } function DIV270(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV270(a, b, "div: /"); } function DIV270(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD552(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return MOD552(a, b, "mod: %"); } function MOD552(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } 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 // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _not_entered410 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered581 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered410; } modifier NONREENTRANT577() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered581, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered581; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered410; } } interface IERC20 { function TOTALSUPPLY402() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF653(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER134(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE619(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE305(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM0(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER881(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL173(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library Address { function ISCONTRACT661(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function TOPAYABLE190(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE489(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER297(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.TRANSFER134.selector, to, value)); } function SAFETRANSFERFROM429(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.TRANSFERFROM0.selector, from, to, value)); } function SAFEAPPROVE484(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE619(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.APPROVE305.selector, spender, value)); } function SAFEINCREASEALLOWANCE405(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE619(address(this), spender).ADD750(value); CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.APPROVE305.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE743(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE619(address(this), spender).SUB186(value, "SafeERC20: < 0"); CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.APPROVE305.selector, spender, newAllowance)); } function CALLOPTIONALRETURN600(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT661(), "SafeERC20: !contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: !succeed"); } } } library KperNetworkLibrary { function GETRESERVE107(address pair, address reserve) external view returns (uint) { //inject NONSTANDARD NAMING (uint _r0, uint _r1,) = IUniswapV2Pair(pair).GETRESERVES90(); if (IUniswapV2Pair(pair).TOKEN0518() == reserve) { return _r0; } else if (IUniswapV2Pair(pair).TOKEN1343() == reserve) { return _r1; } else { return 0; } } } interface IUniswapV2Pair { event APPROVAL173(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER881(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME679() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL555() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS187() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY402() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF653(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE619(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE305(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER134(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM0(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR360() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH617() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES5(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT744(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT880(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN642(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP530( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY128() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY30() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0518() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1343() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES90() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST484() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST567() external view returns (uint); //inject NONSTANDARD NAMING function KLAST695() external view returns (uint); //inject NONSTANDARD NAMING function MINT553(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN246(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP955(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM112(address to) external; //inject NONSTANDARD NAMING function SYNC19() external; //inject NONSTANDARD NAMING function INITIALIZE501(address, address) external; //inject NONSTANDARD NAMING } interface IGovernance { function PROPOSEJOB67(address job) external; //inject NONSTANDARD NAMING } interface IKperNetworkHelper { function GETQUOTELIMIT193(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING } contract KperNetwork is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; IKperNetworkHelper public KPRH; string public constant name59 = "Kper.Network"; //inject NONSTANDARD NAMING string public constant symbol586 = "KPER"; //inject NONSTANDARD NAMING uint8 public constant decimals310 = 18; //inject NONSTANDARD NAMING uint public totalSupply = 0; // Initial 0 mapping (address => address) public delegates; mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; bytes32 public constant domain_typehash648 = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); //inject NONSTANDARD NAMING bytes32 public immutable DOMAINSEPARATOR; bytes32 public constant delegation_typehash691 = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); //inject NONSTANDARD NAMING bytes32 public constant permit_typehash982 = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); //inject NONSTANDARD NAMING mapping (address => uint) public nonces; event DELEGATECHANGED7(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); //inject NONSTANDARD NAMING event DELEGATEVOTESCHANGED30(address indexed delegate, uint previousBalance, uint newBalance); //inject NONSTANDARD NAMING struct Checkpoint { uint32 fromBlock; uint votes; } function DELEGATE839(address delegatee) public { //inject NONSTANDARD NAMING _DELEGATE446(msg.sender, delegatee); } function DELEGATEBYSIG540(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING bytes32 structHash = keccak256(abi.encode(delegation_typehash691, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(now <= expiry, "delegateBySig: expired"); _DELEGATE446(signatory, delegatee); } function GETCURRENTVOTES464(address account) external view returns (uint) { //inject NONSTANDARD NAMING uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function GETPRIORVOTES822(address account, uint blockNumber) public view returns (uint) { //inject NONSTANDARD NAMING require(blockNumber < block.number, "getPriorVotes:"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _DELEGATE446(address delegator, address delegatee) internal { //inject NONSTANDARD NAMING address currentDelegate = delegates[delegator]; uint delegatorBalance = votes[delegator].ADD750(bonds[delegator][address(this)]); delegates[delegator] = delegatee; emit DELEGATECHANGED7(delegator, currentDelegate, delegatee); _MOVEDELEGATES153(currentDelegate, delegatee, delegatorBalance); } function _MOVEDELEGATES153(address srcRep, address dstRep, uint amount) internal { //inject NONSTANDARD NAMING if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.SUB186(amount, "_moveVotes: underflows"); _WRITECHECKPOINT898(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.ADD750(amount); _WRITECHECKPOINT898(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _WRITECHECKPOINT898(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { //inject NONSTANDARD NAMING uint32 blockNumber = SAFE32446(block.number, "_writeCheckpoint: 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DELEGATEVOTESCHANGED30(delegatee, oldVotes, newVotes); } function SAFE32446(uint n, string memory errorMessage) internal pure returns (uint32) { //inject NONSTANDARD NAMING require(n < 2**32, errorMessage); return uint32(n); } event TRANSFER881(address indexed from, address indexed to, uint amount); //inject NONSTANDARD NAMING event APPROVAL173(address indexed owner, address indexed spender, uint amount); //inject NONSTANDARD NAMING event SUBMITJOB626(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event APPLYCREDIT477(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event REMOVEJOB82(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event UNBONDJOB739(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event JOBADDED910(address indexed job, uint block, address governance); //inject NONSTANDARD NAMING event JOBREMOVED937(address indexed job, uint block, address governance); //inject NONSTANDARD NAMING event KEEPERWORKED480(address indexed credit, address indexed job, address indexed keeper, uint block, uint amount); //inject NONSTANDARD NAMING event KEEPERBONDING674(address indexed keeper, uint block, uint active, uint bond); //inject NONSTANDARD NAMING event KEEPERBONDED647(address indexed keeper, uint block, uint activated, uint bond); //inject NONSTANDARD NAMING event KEEPERUNBONDING556(address indexed keeper, uint block, uint deactive, uint bond); //inject NONSTANDARD NAMING event KEEPERUNBOUND602(address indexed keeper, uint block, uint deactivated, uint bond); //inject NONSTANDARD NAMING event KEEPERSLASHED412(address indexed keeper, address indexed slasher, uint block, uint slash); //inject NONSTANDARD NAMING event KEEPERDISPUTE615(address indexed keeper, uint block); //inject NONSTANDARD NAMING event KEEPERRESOLVED375(address indexed keeper, uint block); //inject NONSTANDARD NAMING event ADDCREDIT188(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); //inject NONSTANDARD NAMING uint constant public bond875 = 3 days; //inject NONSTANDARD NAMING uint constant public unbond293 = 14 days; //inject NONSTANDARD NAMING uint constant public liquiditybond59 = 3 days; //inject NONSTANDARD NAMING uint constant public fee898 = 30; //inject NONSTANDARD NAMING uint constant public base419 = 10000; //inject NONSTANDARD NAMING address constant public eth194 = address(0xE); //inject NONSTANDARD NAMING mapping(address => mapping(address => uint)) public bondings; mapping(address => mapping(address => uint)) public unbondings; mapping(address => mapping(address => uint)) public partialUnbonding; mapping(address => mapping(address => uint)) public pendingbonds; mapping(address => mapping(address => uint)) public bonds; mapping(address => uint) public votes; uint public totalBonded = 0; mapping(address => uint) public firstSeen; mapping(address => bool) public disputes; mapping(address => uint) public lastJob; mapping(address => uint) public workCompleted; mapping(address => bool) public jobs; mapping(address => mapping(address => uint)) public credits; mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; mapping(address => uint) public jobProposalDelay; mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; mapping(address => bool) public keepers; mapping(address => bool) public blacklist; address[] public keeperList; address[] public jobList; address public governance; address public pendingGovernance; mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor(address _kph) public { // Set governance for this token governance = msg.sender; DOMAINSEPARATOR = keccak256(abi.encode(domain_typehash648, keccak256(bytes(name59)), _GETCHAINID109(), address(this))); KPRH = IKperNetworkHelper(_kph); } function ADDCREDITETH565(address job) external payable { //inject NONSTANDARD NAMING require(jobs[job], "addCreditETH: !job"); uint _fee = msg.value.MUL249(fee898).DIV270(base419); credits[job][eth194] = credits[job][eth194].ADD750(msg.value.SUB186(_fee)); payable(governance).transfer(_fee); emit ADDCREDIT188(eth194, job, msg.sender, block.number, msg.value); } function ADDCREDIT18(address credit, address job, uint amount) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).BALANCEOF653(address(this)); IERC20(credit).SAFETRANSFERFROM429(msg.sender, address(this), amount); uint _received = IERC20(credit).BALANCEOF653(address(this)).SUB186(_before); uint _fee = _received.MUL249(fee898).DIV270(base419); credits[job][credit] = credits[job][credit].ADD750(_received.SUB186(_fee)); IERC20(credit).SAFETRANSFER297(governance, _fee); emit ADDCREDIT188(credit, job, msg.sender, block.number, _received); } function ADDVOTES465(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addVotes: !gov"); _ACTIVATE236(voter, address(this)); votes[voter] = votes[voter].ADD750(amount); totalBonded = totalBonded.ADD750(amount); _MOVEDELEGATES153(address(0), delegates[voter], amount); } function REMOVEVOTES245(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addVotes: !gov"); votes[voter] = votes[voter].SUB186(amount); totalBonded = totalBonded.SUB186(amount); _MOVEDELEGATES153(delegates[voter], address(0), amount); } function ADDKPRCREDIT8(address job, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addKPRCredit: !gov"); require(jobs[job], "addKPRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].ADD750(amount); _MINT726(address(this), amount); emit ADDCREDIT188(address(this), job, msg.sender, block.number, amount); } function APPROVELIQUIDITY363(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "approveLiquidity: !gov"); require(!liquidityAccepted[liquidity], "approveLiquidity: !pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } function REVOKELIQUIDITY704(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "revokeLiquidity: !gov"); liquidityAccepted[liquidity] = false; } function PAIRS99() external view returns (address[] memory) { //inject NONSTANDARD NAMING return liquidityPairs; } function ADDLIQUIDITYTOJOB689(address liquidity, address job, uint amount) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).SAFETRANSFERFROM429(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].ADD750(amount); liquidityApplied[msg.sender][liquidity][job] = now.ADD750(liquiditybond59); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].ADD750(amount); if (!jobs[job] && jobProposalDelay[job] < now) { IGovernance(governance).PROPOSEJOB67(job); jobProposalDelay[job] = now.ADD750(unbond293); } emit SUBMITJOB626(job, liquidity, msg.sender, block.number, amount); } function APPLYCREDITTOJOB508(address provider, address liquidity, address job) external { //inject NONSTANDARD NAMING require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(liquidityApplied[provider][liquidity][job] < now, "credit: bonding"); uint _liquidity = KperNetworkLibrary.GETRESERVE107(liquidity, address(this)); uint _credit = _liquidity.MUL249(liquidityAmount[provider][liquidity][job]).DIV270(IERC20(liquidity).TOTALSUPPLY402()); _MINT726(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].ADD750(_credit); liquidityAmount[provider][liquidity][job] = 0; emit APPLYCREDIT477(job, liquidity, provider, block.number, _credit); } function UNBONDLIQUIDITYFROMJOB746(address liquidity, address job, uint amount) external { //inject NONSTANDARD NAMING require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now.ADD750(unbond293); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].ADD750(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds"); uint _liquidity = KperNetworkLibrary.GETRESERVE107(liquidity, address(this)); uint _credit = _liquidity.MUL249(amount).DIV270(IERC20(liquidity).TOTALSUPPLY402()); if (_credit > credits[job][address(this)]) { _BURN941(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _BURN941(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].SUB186(_credit); } emit UNBONDJOB739(job, liquidity, msg.sender, block.number, amount); } function REMOVELIQUIDITYFROMJOB500(address liquidity, address job) external { //inject NONSTANDARD NAMING require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].SUB186(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).SAFETRANSFER297(msg.sender, _amount); emit REMOVEJOB82(job, liquidity, msg.sender, block.number, _amount); } function MINT553(uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "mint: !gov"); _MINT726(governance, amount); } function BURN246(uint amount) external { //inject NONSTANDARD NAMING _BURN941(msg.sender, amount); } function _MINT726(address dst, uint amount) internal { //inject NONSTANDARD NAMING // mint the amount totalSupply = totalSupply.ADD750(amount); // transfer the amount to the recipient balances[dst] = balances[dst].ADD750(amount); emit TRANSFER881(address(0), dst, amount); } function _BURN941(address dst, uint amount) internal { //inject NONSTANDARD NAMING require(dst != address(0), "_burn: zero address"); balances[dst] = balances[dst].SUB186(amount, "_burn: exceeds balance"); totalSupply = totalSupply.SUB186(amount); emit TRANSFER881(dst, address(0), amount); } function WORKED503(address keeper) external { //inject NONSTANDARD NAMING WORKRECEIPT237(keeper, KPRH.GETQUOTELIMIT193(_gasUsed.SUB186(gasleft()))); } function WORKRECEIPT237(address keeper, uint amount) public { //inject NONSTANDARD NAMING require(jobs[msg.sender], "workReceipt: !job"); require(amount <= KPRH.GETQUOTELIMIT193(_gasUsed.SUB186(gasleft())), "workReceipt: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].SUB186(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; _REWARD950(keeper, amount); workCompleted[keeper] = workCompleted[keeper].ADD750(amount); emit KEEPERWORKED480(address(this), msg.sender, keeper, block.number, amount); } function RECEIPT523(address credit, address keeper, uint amount) external { //inject NONSTANDARD NAMING require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][credit] = credits[msg.sender][credit].SUB186(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; IERC20(credit).SAFETRANSFER297(keeper, amount); emit KEEPERWORKED480(credit, msg.sender, keeper, block.number, amount); } function RECEIPTETH18(address keeper, uint amount) external { //inject NONSTANDARD NAMING require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][eth194] = credits[msg.sender][eth194].SUB186(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KEEPERWORKED480(eth194, msg.sender, keeper, block.number, amount); } function _REWARD950(address _from, uint _amount) internal { //inject NONSTANDARD NAMING bonds[_from][address(this)] = bonds[_from][address(this)].ADD750(_amount); totalBonded = totalBonded.ADD750(_amount); _MOVEDELEGATES153(address(0), delegates[_from], _amount); emit TRANSFER881(msg.sender, _from, _amount); } function _BOND529(address bonding, address _from, uint _amount) internal { //inject NONSTANDARD NAMING bonds[_from][bonding] = bonds[_from][bonding].ADD750(_amount); if (bonding == address(this)) { totalBonded = totalBonded.ADD750(_amount); _MOVEDELEGATES153(address(0), delegates[_from], _amount); } } function _UNBOND647(address bonding, address _from, uint _amount) internal { //inject NONSTANDARD NAMING bonds[_from][bonding] = bonds[_from][bonding].SUB186(_amount); if (bonding == address(this)) { totalBonded = totalBonded.SUB186(_amount); _MOVEDELEGATES153(delegates[_from], address(0), _amount); } } function ADDJOB840(address job) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addJob: !gov"); require(!jobs[job], "addJob: job known"); jobs[job] = true; jobList.push(job); emit JOBADDED910(job, block.number, msg.sender); } function GETJOBS254() external view returns (address[] memory) { //inject NONSTANDARD NAMING return jobList; } function REMOVEJOB380(address job) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "removeJob: !gov"); jobs[job] = false; emit JOBREMOVED937(job, block.number, msg.sender); } function SETKPERNETWORKHELPER865(IKperNetworkHelper _kprh) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setKperNetworkHelper: !gov"); KPRH = _kprh; } function SETGOVERNANCE939(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } function ACCEPTGOVERNANCE630() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } function ISKEEPER927(address keeper) external returns (bool) { //inject NONSTANDARD NAMING _gasUsed = gasleft(); return keepers[keeper]; } function ISMINKEEPER163(address keeper, uint minBond, uint earned, uint age) external returns (bool) { //inject NONSTANDARD NAMING _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].ADD750(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.SUB186(firstSeen[keeper]) >= age; } function ISBONDEDKEEPER241(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { //inject NONSTANDARD NAMING _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.SUB186(firstSeen[keeper]) >= age; } function BOND260(address bonding, uint amount) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(!blacklist[msg.sender], "bond: blacklisted"); bondings[msg.sender][bonding] = now.ADD750(bond875); if (bonding == address(this)) { _TRANSFERTOKENS224(msg.sender, address(this), amount); } else { uint _before = IERC20(bonding).BALANCEOF653(address(this)); IERC20(bonding).SAFETRANSFERFROM429(msg.sender, address(this), amount); amount = IERC20(bonding).BALANCEOF653(address(this)).SUB186(_before); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].ADD750(amount); emit KEEPERBONDING674(msg.sender, block.number, bondings[msg.sender][bonding], amount); } function GETKEEPERS116() external view returns (address[] memory) { //inject NONSTANDARD NAMING return keeperList; } function ACTIVATE41(address bonding) external { //inject NONSTANDARD NAMING require(!blacklist[msg.sender], "activate: blacklisted"); require(bondings[msg.sender][bonding] != 0 && bondings[msg.sender][bonding] < now, "activate: bonding"); _ACTIVATE236(msg.sender, bonding); } function _ACTIVATE236(address keeper, address bonding) internal { //inject NONSTANDARD NAMING if (firstSeen[keeper] == 0) { firstSeen[keeper] = now; keeperList.push(keeper); lastJob[keeper] = now; } keepers[keeper] = true; _BOND529(bonding, keeper, pendingbonds[keeper][bonding]); pendingbonds[keeper][bonding] = 0; emit KEEPERBONDED647(keeper, block.number, block.timestamp, bonds[keeper][bonding]); } function UNBOND442(address bonding, uint amount) external { //inject NONSTANDARD NAMING unbondings[msg.sender][bonding] = now.ADD750(unbond293); _UNBOND647(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].ADD750(amount); emit KEEPERUNBONDING556(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } function WITHDRAW592(address bonding) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _TRANSFERTOKENS224(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { IERC20(bonding).SAFETRANSFER297(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KEEPERUNBOUND602(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } function DISPUTE590(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "dispute: !gov"); disputes[keeper] = true; emit KEEPERDISPUTE615(keeper, block.number); } function SLASH39(address bonded, address keeper, uint amount) public NONREENTRANT577 { //inject NONSTANDARD NAMING require(msg.sender == governance, "slash: !gov"); if (bonded == address(this)) { _TRANSFERTOKENS224(address(this), governance, amount); } else { IERC20(bonded).SAFETRANSFER297(governance, amount); } _UNBOND647(bonded, keeper, amount); disputes[keeper] = false; emit KEEPERSLASHED412(keeper, msg.sender, block.number, amount); } function REVOKE253(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "slash: !gov"); keepers[keeper] = false; blacklist[keeper] = true; SLASH39(address(this), keeper, bonds[keeper][address(this)]); } function RESOLVE476(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "resolve: !gov"); disputes[keeper] = false; emit KEEPERRESOLVED375(keeper, block.number); } function ALLOWANCE619(address account, address spender) external view returns (uint) { //inject NONSTANDARD NAMING return allowances[account][spender]; } function APPROVE305(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING allowances[msg.sender][spender] = amount; emit APPROVAL173(msg.sender, spender, amount); return true; } function PERMIT744(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { //inject NONSTANDARD NAMING bytes32 structHash = keccak256(abi.encode(permit_typehash982, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(now <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit APPROVAL173(owner, spender, amount); } function BALANCEOF653(address account) external view returns (uint) { //inject NONSTANDARD NAMING return balances[account]; } function TRANSFER134(address dst, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFERTOKENS224(msg.sender, dst, amount); return true; } function TRANSFERFROM0(address src, address dst, uint amount) external returns (bool) { //inject NONSTANDARD NAMING address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.SUB186(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit APPROVAL173(src, spender, newAllowance); } _TRANSFERTOKENS224(src, dst, amount); return true; } function _TRANSFERTOKENS224(address src, address dst, uint amount) internal { //inject NONSTANDARD NAMING require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].SUB186(amount, "_transferTokens: exceeds balance"); balances[dst] = balances[dst].ADD750(amount, "_transferTokens: overflows"); emit TRANSFER881(src, dst, amount); } function _GETCHAINID109() internal pure returns (uint) { //inject NONSTANDARD NAMING uint chainId; assembly { chainId := chainid() } return chainId; } }
inject NONSTANDARD NAMING
function WORKED503(address keeper) external {
12,787,914
./full_match/1/0xCf3b485bd11BCa74103D7D3534503bAD3fbdaC6d/sources/contracts/JBFundingCycleStore.sol
/ Get a reference to the latest funding cycle configuration. Resolve the funding cycle for the latest configuration.
function currentBallotStateOf(uint256 _projectId) external view override returns (JBBallotState) { uint256 _fundingCycleConfiguration = latestConfigurationOf[_projectId]; JBFundingCycle memory _fundingCycle = _getStructFor(_projectId, _fundingCycleConfiguration); return _ballotStateOf( _projectId, _fundingCycle.configuration, _fundingCycle.start, _fundingCycle.basedOn ); } Configures the next eligible funding cycle for the specified project. @dev Only a project's current controller can configure its funding cycles. @param _projectId The ID of the project being configured. @param _data The funding cycle configuration data. @param _metadata Arbitrary extra data to associate with this funding cycle configuration that's not used within. @param _mustStartAtOrAfter The time before which the initialized funding cycle cannot start. @return The funding cycle that the configuration will take effect during.
17,049,527
pragma solidity 0.4.21; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @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 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/token/MintableTokenWithMinters.sol /** * @title Mintable Token with minters * @dev MintableToken, mintable by appointed minters */ contract MintableTokenWithMinters is MintableToken { mapping (address => bool) public minters; event MinterAdded(address indexed minter); event MinterRemoved(address indexed minter); /** * @dev Throws if called by any account other than the minter. */ modifier onlyMinter() { require(minters[msg.sender] == true); _; } /** * @dev The MintableToken constructor sets the first `minter` of the contract to the owner * account. */ function MintableTokenWithMinters() public { minters[owner] = true; // owner is minter } /** * @dev Function to mint tokens * @param _to The address to send new tokens to. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyMinter canMint returns (bool) { // return super.mint(_to, _amount); // not used due to onlyOwner modifier totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Allows the owner to add a new minter. * @param newMinter The address to add as a minter. */ function addMinter(address newMinter) public onlyOwner { require(newMinter != address(0)); // not empty require(minters[newMinter] != true); // not already a minter emit MinterAdded(newMinter); minters[newMinter] = true; } /** * @dev Allows the owner to remove an existing minter. * @param minter The address to remove as a minter. */ function removeMinter(address minter) public onlyOwner { require(minter != owner); // cannot remove owner require(minters[minter] == true); // already a minter emit MinterRemoved(minter); delete minters[minter]; } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: contracts/EtfToken.sol /** * @title FCTF 10 Coins token */ contract EtfToken is MintableTokenWithMinters, BurnableToken { string public constant name = "FCTF 10 Coins"; string public constant symbol = "10COINS"; uint8 public constant decimals = 8; function EtfToken() public { totalSupply_ = 0; } }
Function to mint tokens _to The address to send new tokens to. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./ return super.mint(_to, _amount); not used due to onlyOwner modifier
function mint(address _to, uint256 _amount) public onlyMinter canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; }
6,774,718
./full_match/1/0x88a5375636ed6e80bF5a277317C416D500BB658b/sources/SpiralChef.sol
Withdraw unlocked tokens.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { require(block.timestamp > lockUntil); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 postAmount = user.amount - _amount; require(postAmount >= 0 && _amount > 0, "withdraw: not good"); updatePool(_pid); if (rwt.length > 0) { _addToClaimable(_pid, msg.sender); uint256[] memory _poolAccRew = poolInfo[_pid].accRwtPerShare; for (uint i=0; i < rwt.length; i++){ if (user.claimableRWT[i] > 0) { safeRWTTransfer(i, msg.sender, user.claimableRWT[i]); user.claimableRWT[i] = 0; user.rewardDebt[i] = postAmount * _poolAccRew[i] / 1e30; } } } user.amount = postAmount; poolInfo[_pid].lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
3,035,298
./full_match/5/0x24EbD77985F015DefEe0579449dAcbe58c1Ac25c/sources/project:/contracts/MedicalRecordAccessControl.sol
Deny access (though it might not have been granted yet) Clear the access request
function denyAccess(uint256 patientID, uint256 doctorID) public onlyOwner { require( patients[patientID].doctorAccessRequests[doctorID], "Doctor did not request access or access was already granted" ); patients[patientID].doctorHasAccess[doctorID] = false; delete patients[patientID].doctorAccessRequests[doctorID]; emit AccessDenied(patientID, doctorID); }
1,871,915
// SPDX-License-Identifier: MIT pragma solidity ^0.8.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./TokenPaymentSplitter.sol"; interface IOneSplitAudit { function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) external payable returns (uint256 returnAmount); function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns (uint256 returnAmount, uint256[] memory distribution); } interface IPool { /** * @notice Structs */ struct Claim { bytes32 root; uint256 score; bytes32[] proof; } function withdrawProtected( Claim[] memory claims, IERC20 token, uint256 minimumAmount ) external; } contract FeeReceiver is Ownable, TokenPaymentSplitter { using SafeMath for uint256; event FeeConsolidatation( address triggerAccount, IERC20 swapFrom, IERC20 swapTo, uint256 amount, address[] recievedAddresses ); address public swapToToken; address public poolAddress; address public oneSplitAudit; address public stakeAddress; uint256 public stakeThreshold; uint256 public triggerFee; bool public stakeActive; /** * @dev Set a new token to swap to (e.g., stabletoken). **/ function setSwapToToken(address _swapToToken) public onlyOwner { swapToToken = _swapToToken; } /** * @dev Set a new address of fee pool. */ function setPoolAddress(address _poolAddress) public onlyOwner { poolAddress = _poolAddress; } /** * @dev Set a new address of on-chain AMM. */ function setOneSplitAudit(address _oneSplitAudit) public onlyOwner { oneSplitAudit = _oneSplitAudit; } /** * @dev Set a new address of stake contract. */ function setStakeAddress(address _stakeAddress) public onlyOwner { stakeAddress = _stakeAddress; } /** * @dev Set a new threshold for stake contract token balance. */ function setStakeThreshold(uint256 _stakeThreshold) public onlyOwner { stakeThreshold = _stakeThreshold; } /** * @dev Set a if staking is required. */ function setStakeActive(bool _switch) public onlyOwner { stakeActive = _switch; } /** * @dev Set a new fee (perentage 0 - 100) for calling the ConsolidateFeeToken function. */ function setTriggerFee(uint256 _triggerFee) public onlyOwner { triggerFee = _triggerFee; } constructor( address _swapToToken, address _poolAddress, address _oneSplitAudit, uint256 _triggerFee, address[] memory payees, uint256[] memory shares_ ) TokenPaymentSplitter(payees, shares_) { swapToToken = _swapToToken; poolAddress = _poolAddress; oneSplitAudit = _oneSplitAudit; triggerFee = _triggerFee; } /** * @dev Set a new fee (perentage 0 - 100) for calling the ConsolidateFeeToken function. * @param _claims The claim struct necessary to withdraw from the fee pool. * @param _swapFromToken The token from the fee pool to be swapped from. * @param _amount The amount of token from the fee pool to be swapped and distributed. */ function ConsolidateFeeToken( IPool.Claim[] memory _claims, address _swapFromToken, uint256 _amount ) public { if (stakeActive) { require(checkStake(msg.sender), "Not enough staked tokens"); } // Calls the withdrawProtected function from the fee pool to transfer tokens into this contract. IPool(poolAddress).withdrawProtected( _claims, IERC20(_swapFromToken), _amount ); // Calls the getExpectedReturn function from the on-chain AMM and catches result. (uint256 _expected, uint256[] memory _distribution) = IOneSplitAudit( oneSplitAudit ).getExpectedReturn( IERC20(_swapFromToken), IERC20(swapToToken), _amount, 0, 0 ); // Calls the swap function from the on-chain AMM to swap token from fee pool into (stable)token. IOneSplitAudit(oneSplitAudit).swap( IERC20(_swapFromToken), IERC20(swapToToken), _amount, _expected, _distribution, 0 ); // Calculates trigger reward amount and transfers to msg.sender. uint256 triggerFeeAmount = _amount.mul(triggerFee).div(100); _transferErc20(msg.sender, swapToToken, triggerFeeAmount); // Transfers remaining amount to reward pool address(es). uint256 rewardPoolAmount = _amount.sub(triggerFeeAmount); for (uint256 i = 0; i < _payees.length; i++) { uint256 distributionRatio = (_shares[_payees[i]] / _totalShares); _transferErc20( _payees[i], swapToToken, rewardPoolAmount.mul(distributionRatio) ); } emit FeeConsolidatation( msg.sender, IERC20(_swapFromToken), IERC20(swapToToken), _amount, _payees ); } /** * @dev Internal function to transfer ERC20 held in the contract. * * */ function _transferErc20( address _recipient, address _tokenContract, uint256 _returnAmount ) internal { IERC20 erc; erc = IERC20(_tokenContract); require( erc.balanceOf(address(this)) >= _returnAmount, "Not enough funds to transfer" ); erc.transfer(_recipient, _returnAmount); } /** * @dev Checks if an address is staking tokens at or above threshold. * @param _staker Address to check if token staker. */ function checkStake(address _staker) internal view returns(bool) { IERC20 erc; erc = IERC20(stakeAddress); bool verifiedStaker = (erc.balanceOf(_staker) >= stakeThreshold) ? true : false; return verifiedStaker; } /** * @dev Add a recipient to receive payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _shares Amount of shares to determine th proportion of payout received. */ function addPayee(address _account, uint256 _shares) public onlyOwner { _addPayee(_account, _shares); } /** * @dev Remove a recipient from receiving payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _index Index number of the recipient in the array of recipients. */ function removePayee(address _account, uint256 _index) public onlyOwner { _removePayee(_account, _index); } }
Remove a recipient from receiving payouts from the consolidateFeeToken function. _account Address of the recipient. _index Index number of the recipient in the array of recipients./
function removePayee(address _account, uint256 _index) public onlyOwner { _removePayee(_account, _index); }
6,419,347
./full_match/83/0x7321b5bAb3052bb873847f36C1aAa0917CE7Bb82/sources/contracts/base/token/MinterUpgradeable.sol
将循环供量 = token总代币供应 - veNFT锁定量 - veDist余额 - 当前合约余额 从流通中排除 veDist 代币余额 - 用户无法在没有锁定的情况下领取它们 逾期索赔将导致错误的流通供应计算 排除铸币厂余额,显然是锁定的
function _circulatingSupply() internal view returns (uint) { return _token.balanceOf(address(_veDist())) - _token.balanceOf(address(this)); }
9,564,868
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Interface to the RandomWalkNFT contract. abstract contract IRandomWalkNFT is IERC721 { uint256 public numWithdrawals; address public lastMinter; uint256 public lastMintTime; uint256 public nextTokenId; function mint() public payable virtual; function withdraw() public virtual; function getMintPrice() public view virtual returns (uint256); function timeUntilWithdrawal() public view virtual returns (uint256); } contract ImpishDAO is ERC20, ERC20Burnable, Ownable, IERC721Receiver, ReentrancyGuard { // How many ERC20 tokens per ETH. uint256 public constant MINT_RATIO = 1000; // The minimum price that the NFT will be sold // Note that even though it says 1 ether, it is actual 1 IMPISH tokens, // since IMPISH also has 18 decimals uint256 public constant NFT_MIN_PRICE = 1 * 1 ether; // The price of secondary sales by the DAO decays over this time linearly. uint256 private constant ONE_MONTH = 30 * 24 * 3600; // The (hard-coded) Randomwalk NFT round that we're playing. If we want to play // another round, we'll deploy another contract. uint256 public constant RWNFT_ROUND = 0; // Interface to the underlying NFT contract. Filled in the constructor IRandomWalkNFT public rwNFT; // The state that the contract is in. Starts off PAUSED // PAUSED = 0; // Contract has been paused, No minting, only withdrawal. Will be used in an emergency // PLAYING = 1; // DAO is playing the game with RandomWalkNFT // FINISHED_WIN = 2; // This round of RandomWalkNFT has finished, and the DAO won // FINISHED_LOST = 3; // This round of RandomWalkNFT has finished, and the DAO lost. uint8 public contractState = 0; // Event for when NFT is available for sale or sold // tokenID, startPrice, forSale event NFTForSaleTx(uint256, uint256, bool); struct NFTForSale { uint256 startTime; // When the NFT was first available, used to determine price uint256 startPrice; // in IMPISH tokens. } mapping(uint256 => NFTForSale) public forSale; constructor(address _rwNFTaddress) ERC20("ImpishDAO", "IMPISH") { rwNFT = IRandomWalkNFT(_rwNFTaddress); // The contract is playable as soon as it is deployed. contractState = 1; } // Pause is a one-way function. Can't unpause it. function pause() public onlyOwner { contractState = 0; } // Modifiers modifier whenNotPaused() { require(contractState != 0, "Paused"); _; } modifier whenPlaying() { require(contractState == 1, "NotPlaying"); _; } // Returns if the last minter of the RandomWalkNFT is us. function areWeWinning() public view returns (bool) { return rwNFT.lastMinter() == address(this); } // For safety, the contract limits how much ETH it holds. It is higher of // 100 ether or // 10 times the next mint price function getMaxEth() public view returns (uint256) { uint256 maxETH = rwNFT.getMintPrice() * 10; if (maxETH < 100 ether) { maxETH = 100 ether; } return maxETH; } // How much additional ETH the contract can accept. // Note, if you call this inside a payable function, this will include the msg.value // of that function, so it might not be exactly what you're expecting. function getMaxEthThatCanBeDeposit() public view returns (uint256) { uint256 maxEth = getMaxEth(); if (address(this).balance >= maxEth) { return 0; } else { return maxEth - address(this).balance; } } // What is the price (in IMPISH tokens) that the given tokenID is available for purchase. function buyNFTPrice(uint256 tokenID) public view returns (uint256) { uint256 startTime = forSale[tokenID].startTime; uint256 startPrice = forSale[tokenID].startPrice; require(startTime > 0, "TokenID not owned"); uint256 elapsedTime = block.timestamp - startTime; if (elapsedTime >= ONE_MONTH || startPrice < NFT_MIN_PRICE) { // Don't let price fall below the minimum price of NFT sales. return NFT_MIN_PRICE; } else { // Linearly decays over a month return NFT_MIN_PRICE + (((ONE_MONTH - elapsedTime) * (startPrice - NFT_MIN_PRICE)) / ONE_MONTH); } } // Obtain the next Random Walk NFT. Internal, so needs to be called from deposit() function _mintNextRwNFT() internal whenPlaying { // Make sure that we're still paying the correct round require(rwNFT.numWithdrawals() == RWNFT_ROUND, "Not Playable"); // If we're already winning, don't bid against ourselves require(!areWeWinning(), "Already winning"); // Next mint price from the RandomWalkNFT contract uint256 mintPrice = rwNFT.getMintPrice(); // The newly minted NFT will have this ID. uint256 mintedNFTTokenId = rwNFT.nextTokenId(); // Call into the other contract and mint it. Re-entrancy risk here is minimal, // since this contract is not upgradable and this particular method doesn't do any // funky stuff. rwNFT.mint{value: mintPrice}(); // And put it up for sale (assuming the mint succeeds). // Starting price is 10x the mint price, and decreases to 0.0001 ETH over one month (Dutch Auction) // Remember to multiply by MINT_RATIO, because price is in IMPISH uint256 forSalePrice = mintPrice * MINT_RATIO * 10; forSale[mintedNFTTokenId] = NFTForSale(block.timestamp, forSalePrice); // Emit event emit NFTForSaleTx(mintedNFTTokenId, forSalePrice, true); } // Buy a NFT from the contract. It will automatically deduct the price from the // sender's balance. function buyNFT(uint256 tokenID) public nonReentrant { uint256 price = buyNFTPrice(tokenID); // Ensure sender has enough tokens require(balanceOf(msg.sender) >= price, "Not enough IMPISH"); // Burn the tokens and delete the item from the for-sale list _burn(msg.sender, price); delete forSale[tokenID]; // Transfer to sender rwNFT.safeTransferFrom(address(this), msg.sender, tokenID); // Emit event emit NFTForSaleTx(tokenID, price, false); } // Deposit ETH into the contract and mint IMPISH tokens function deposit() public payable whenNotPaused whenPlaying nonReentrant { // For protection, don't accept too much ETH. Note that since this is a payable // function, address(this).balance already includes the ETH sent to this function. require(address(this).balance <= getMaxEth(), "Too much ETH"); // Mint tokens if (msg.value > 0) { address to = msg.sender; uint256 mintAmount = msg.value * MINT_RATIO; _mint(to, mintAmount); } // Check if the current round is active if (rwNFT.numWithdrawals() != RWNFT_ROUND) { // We lost, since the winner has claimed the winnings and the round has advanced contractState = 3; return; } // Check if there is any housekeeping to be done. if (rwNFT.timeUntilWithdrawal() == 0 && areWeWinning()) { // We Won! So withdraw the funds from the RandomWalkNFT contract. rwNFT.withdraw(); contractState = 2; return; } if (!areWeWinning()) { // Check if we have enough to mint the next NFT if (address(this).balance >= rwNFT.getMintPrice()) { _mintNextRwNFT(); return; } } } // If the round is finished or paused, allow redeeming IMPISH tokens for the contract's ETH. function redeem() public nonReentrant { require(contractState != 1, "Can't redeem while playing"); require(totalSupply() > 0, "Empty!"); uint256 tokens = balanceOf(msg.sender); require(tokens > 0, "Nothing to redeem"); uint256 contractBalance = address(this).balance; require(contractBalance > 0, "Contract Empty!"); uint256 toRedeem = (tokens * address(this).balance) / totalSupply(); // Burn tokens, _burn(msg.sender, tokens); // Last, send ether back (bool success, ) = msg.sender.call{value: toRedeem}(""); require(success, "Transfer failed."); } // Default payable function, so the contract can accept winnings via rwNFT.withdraw() event Received(address, uint256); receive() external payable { emit Received(msg.sender, msg.value); } // Function that marks this contract can accept incoming NFT transfers function onERC721Received( address, address, uint256, bytes calldata ) public view returns (bytes4) { // Only accept NFT transfers from RandomWalkNFT require(msg.sender == address(rwNFT), "NFT not recognized"); // Return this value to accept the NFT return IERC721Receiver.onERC721Received.selector; } }
Returns if the last minter of the RandomWalkNFT is us.
function areWeWinning() public view returns (bool) { return rwNFT.lastMinter() == address(this); }
15,797,472
/// This is inspired by and based on CompoundBasicProxy.sol by DeFi Saver /// reference: https://etherscan.io/address/0x336b3919a10ced553c75db18cd285335b8e8ed38#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./IComptroller.sol"; import "./ICToken.sol"; import "./ICEther.sol"; contract FCompoundActions { // prettier-ignore address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // prettier-ignore address public constant CETH_ADDR = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; // prettier-ignore address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice User deposits tokens to the DSProxy /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public { IERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } /// @notice User withdraws tokens from the DSProxy /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn function withdraw(address _tokenAddr, uint256 _amount) public { if (_tokenAddr == ETH_ADDR) { msg.sender.transfer(_amount); } else { IERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } } /// @notice DSProxy borrows tokens from the Compound protocol /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed function borrow(address _cTokenAddr, uint256 _amount) public { require( ICToken(_cTokenAddr).borrow(_amount) == 0, "FCompoundActions: borrow failed" ); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback function repayBorrow(address _cTokenAddr, uint256 _amount) public payable { uint256 debt = ICToken(_cTokenAddr).borrowBalanceCurrent(address(this)); // If given `_amount` is greater than current debt, set `_amount` to current debt otherwise repay will fail if (_amount > debt) { _amount = debt; } if (_cTokenAddr == CETH_ADDR) { uint256 ethReceived = msg.value; ICEther(_cTokenAddr).repayBorrow{value: _amount}(); // send back the extra eth if (ethReceived > _amount) { msg.sender.transfer(ethReceived.sub(_amount)); } } else { IERC20 token = IERC20(ICToken(_cTokenAddr).underlying()); token.safeTransferFrom(msg.sender, address(this), _amount); if (token.allowance(address(this), _cTokenAddr) < _amount) { token.approve(_cTokenAddr, _amount); } require( ICToken(_cTokenAddr).repayBorrow(_amount) == 0, "FCompoundActions: repay token failed" ); if (msg.value > 0) msg.sender.transfer(msg.value); } } /// @notice Enters the Compound market so it can be used as collateral /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; enterMarkets(markets); } /// @notice Enters the Compound market so these token can be used as collateral /// @param _cTokenAddrs CToken address array to enter market function enterMarkets(address[] memory _cTokenAddrs) public { uint256[] memory errors = IComptroller(COMPTROLLER_ADDR).enterMarkets(_cTokenAddrs); for (uint256 i = 0; i < errors.length; i++) { require(errors[i] == 0, "FCompoundActions: enter markets failed"); } } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { require( IComptroller(COMPTROLLER_ADDR).exitMarket(_cTokenAddr) == 0, "FCompoundActions: exit market failed" ); } }
User deposits tokens to the DSProxy User needs to approve the DSProxy to pull the _tokenAddr tokens _tokenAddr The address of the token to be deposited _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public { IERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); }
1,782,399
pragma solidity ^0.4.11; /** * Copyright 2017 Veterapreneur * * 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. * * */ /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } } contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner { owner = _newOwner; } } contract token { function balanceOf(address owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function burn(uint256 value) returns(bool success); } contract VeteranCoinFree is owned { using SafeMath for uint256; uint public tokensGiven; uint public startDate; uint public endDate; bool giveAwayOpen; token tokenReward; event GiveAwayClosed(); event OpenGiveAway(); event FundTransfer(address _backer, uint _amount, bool _isContribution); event FreeTokens(address _backer, uint _tokenAmt); event Refunded(address _beneficiary, uint _depositedValue); event BurnedExcessTokens(address _beneficiary, uint _amountBurned); mapping(address => uint256) balances; modifier releaseTheHounds(){ if (now >= startDate) _;} modifier isGiveAwayOpen(){ if (giveAwayOpen) _;} function VeteranCoinFree(token _addressOfTokenReward){ startDate = now; endDate = now + 1 years; tokenReward = _addressOfTokenReward; tokensGiven = 0; giveAwayOpen = false; } /** * @dev donations, no tokens only thanks! */ function() payable { donation(msg.sender); } /** * @dev donations, no tokens only thanks! */ function donation(address grantor) public payable { require (grantor != 0x0); balances[grantor] = balances[grantor].add(msg.value); FundTransfer(msg.sender, msg.value, true); } /** * * @dev Everyone can get 10 free tokens per call, enjoy */ function tokenGiveAway() public releaseTheHounds isGiveAwayOpen{ uint256 tokens = 10 * 1 ether; tokensGiven = tokensGiven.add(tokens); tokenReward.transfer(msg.sender, tokens); checkGivenAway(); } /** * * @dev balances of wei sent this contract currently holds * @param _beneficiary how much wei this address sent to contract */ function balanceOf(address _beneficiary) public constant returns (uint256 balance){ return balances[_beneficiary]; } /** * @dev refund any of the donations made to us * */ function refundDonation(address _beneficiary) public onlyOwner{ uint256 depositedValue = balances[_beneficiary]; require(depositedValue > 0); balances[_beneficiary] = 0; _beneficiary.transfer(depositedValue); Refunded(_beneficiary, depositedValue); } /** * * @dev close the give away when the MVP is nigh, or we are out of tokens! */ function closeGiveAway() public onlyOwner{ giveAwayOpen = false; GiveAwayClosed(); } function openGiveAway() public onlyOwner{ giveAwayOpen = true; OpenGiveAway(); } /** * @dev when token's sold = 0, it's over * */ function checkGivenAway() internal { if(tokenReward.balanceOf(this) == 0){ giveAwayOpen = false; GiveAwayClosed(); } } /** * @dev owner can safely withdraw contract value */ function safeWithdrawal() public onlyOwner{ uint256 balance = this.balance; if(owner.send(balance)){ FundTransfer(owner,balance,false); } } // @return true if crowdsale is still going on function giveAwayInProgress() public constant returns (bool) { return giveAwayOpen; } /** * @dev auto burn the tokens * */ function autoBurn() public onlyOwner{ giveAwayOpen = false; uint256 burnPile = tokenReward.balanceOf(this); if(burnPile > 0){ tokenReward.burn(burnPile); BurnedExcessTokens(owner, burnPile); } } }
close the give away when the MVP is nigh, or we are out of tokens!/
function closeGiveAway() public onlyOwner{ giveAwayOpen = false; GiveAwayClosed(); }
12,805,048
./full_match/5/0xC0f19dFa8e2dF07dC9F8BF918d13cEBe1e433fd1/sources/contracts/Gigble.sol
Create a function to create a gig Check if the digital fingerprint already exists
function createGig( string memory _email, string memory _title, string memory _description, uint _deliveryDate, uint _price, bytes32 _digitalFingerprint ) public { for (uint i = 0; i < gigCounter; i++) { require( gigs[i].digitalFingerprint != _digitalFingerprint, "Duplicate content not allowed" ); } gigs[gigCounter] = Gig( _email, _title, _description, _deliveryDate, msg.sender, _price, false, false, false, _digitalFingerprint ); emit GigCreated(gigCounter); gigCounter++; }
1,852,662
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @title EIP-20: ERC-20 Token Standard * * @notice The ERC-20 (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015, * is a Token Standard that implements an API for tokens within Smart Contracts. * * @notice It provides functionalities like to transfer tokens from one account to another, * to get the current token balance of an account and also the total supply of the token available on the network. * Besides these it also has some other functionalities like to approve that an amount of * token from an account can be spent by a third party account. * * @notice If a Smart Contract implements the following methods and events it can be called an ERC-20 Token * Contract and, once deployed, it will be responsible to keep track of the created tokens on Ethereum. * * @notice See https://ethereum.org/en/developers/docs/standards/tokens/erc-20/ * @notice See https://eips.ethereum.org/EIPS/eip-20 */ interface ERC20 { /** * @dev Fired in transfer(), transferFrom() to indicate that token transfer happened * * @param from an address tokens were consumed from * @param to an address tokens were sent to * @param value number of tokens transferred */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Fired in approve() to indicate an approval event happened * * @param owner an address which granted a permission to transfer * tokens on its behalf * @param spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param value amount of tokens granted to transfer on behalf */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @return name of the token (ex.: USD Coin) */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function name() external view returns (string memory); /** * @return symbol of the token (ex.: USDC) */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function symbol() external view returns (string memory); /** * @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`). * * @dev 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; * * @dev 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}. * * @return token decimals */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function decimals() external view returns (uint8); /** * @return the amount of tokens in existence */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of a particular address * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @notice Transfers some tokens to an external address or a smart contract * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner (transaction sender) * * @dev Transaction sender must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); }
EIP-20: ERC-20 Token Standard The ERC-20 (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015, is a Token Standard that implements an API for tokens within Smart Contracts. It provides functionalities like to transfer tokens from one account to another, to get the current token balance of an account and also the total supply of the token available on the network. Besides these it also has some other functionalities like to approve that an amount of token from an account can be spent by a third party account. If a Smart Contract implements the following methods and events it can be called an ERC-20 Token Contract and, once deployed, it will be responsible to keep track of the created tokens on Ethereum./ OPTIONAL - This method can be used to improve usability, but interfaces and other contracts MUST NOT expect these values to be present. function name() external view returns (string memory); OPTIONAL - This method can be used to improve usability, but interfaces and other contracts MUST NOT expect these values to be present. function symbol() external view returns (string memory); OPTIONAL - This method can be used to improve usability, but interfaces and other contracts MUST NOT expect these values to be present. function decimals() external view returns (uint8);
interface ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); pragma solidity ^0.8.4; }
12,763,950
./partial_match/1/0x000000931CF36C464623Bb0EefB6B0C205338d67/sources/TimeLockedController.sol
Transfer ownership of _child to _newOwner Can be used e.g. to upgrade this TimeLockedController contract.
function transferChild(Ownable _child, address _newOwner) public onlyOwner { TransferChildEvent(_child, _newOwner); _child.transferOwnership(_newOwner); }
2,782,063
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.6; import "https://raw.githubusercontent.com/smartcontractkit/chainlink/master/evm-contracts/src/v0.6/ChainlinkClient.sol"; interface PangolinRouter { function swapExactAVAXForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface ERC20 { function balanceOf(address owner) external view returns (uint); function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); } contract Payngolinky is ChainlinkClient { address payable public merchant; address public owner; uint256 private thresholdAmount; PangolinRouter pangoRouter = PangolinRouter(0x2D99ABD9008Dc933ff5c0CD271B88309593aB921); uint256 public lastETHPrice; address private oracle = 0x8CcF5f0f2A45910524b8d17C32D6D1daf3302979; bytes32 private jobId = "9b5a941a2ae040fe8eec5a881dcdc817"; uint256 private fee = 0.1 * 10 ** 17; constructor(address payable merchant_, uint256 threshold_) public { merchant = merchant_; owner = msg.sender; thresholdAmount = threshold_; setChainlinkToken(0x2F0708E5FB96fd1E9F21eAbAd06EE5F337586A02); } function setThreshold(uint256 threshold_) public{ require(msg.sender == merchant); thresholdAmount = threshold_; } function requestPriceData() public returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); // Set the URL to perform the GET request on request.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD"); request.add("path", "RAW.ETH.USD.PRICE"); int timesAmount = 10**18; request.addInt("times", timesAmount); // Sends the request return sendChainlinkRequestTo(oracle, request, fee); } /** * Receive the response in the form of uint256 */ function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) { lastETHPrice = _price; } // merchant always has control over the funds and can withdraw everything function withdrawAll() public { require(msg.sender == merchant); ERC20 WETH = ERC20(0xFE314b188135893A684EE997eDcb81823Ffb575B); ERC20 USDT = ERC20(0xaeC89D2e476a57498b2FB661d3B6667C96BbC11a); if(USDT.balanceOf(address(this)) > 0){ USDT.transfer(merchant,USDT.balanceOf(address(this))); } if(WETH.balanceOf(address(this)) > 0){ WETH.transfer(merchant,WETH.balanceOf(address(this))); } } // either the merchant triggers the swap and USDT transfer at any point // or the owner of the contract (service provider) performs the swap when the threshold set by the merchant is reached // the owner receives compensation for gas fees and a small incentive to realize swap as soon as threshold is reached // access is unrestricted for demonstration purposes function swapAndWithdraw() public { ERC20 WETH = ERC20(0xFE314b188135893A684EE997eDcb81823Ffb575B); ERC20 USDT = ERC20(0xaeC89D2e476a57498b2FB661d3B6667C96BbC11a); uint256 WETHBalance = WETH.balanceOf(address(this)); // turning off access limitations for demonstration purposes //require(msg.sender == merchant || (msg.sender == owner && WETHBalance > thresholdAmount)); requestPriceData(); uint256 amountOutMin = WETHBalance*(lastETHPrice)/10**18; amountOutMin = amountOutMin-amountOutMin/100; address[] memory path = new address[](2); path[0] = 0xFE314b188135893A684EE997eDcb81823Ffb575B; // WETH address path[1] = 0xaeC89D2e476a57498b2FB661d3B6667C96BbC11a; // USDT address //pangoRouter.swapExactAVAXForTokens{value:address(this).balance}(amountOutMin, path, address(this), block.timestamp); WETH.approve(0x2D99ABD9008Dc933ff5c0CD271B88309593aB921,WETHBalance); pangoRouter.swapExactTokensForTokens(WETHBalance,amountOutMin, path, address(this), block.timestamp); uint256 USDTbalance = USDT.balanceOf(address(this)); if(msg.sender == owner && USDTbalance > 5*10**18){ USDT.transfer(owner,5*10**18); // owner gets reimbursed 5$ for initiating swap USDT.transfer(merchant,USDTbalance-5*10**18); // merchant gets the rest } else{ USDT.transfer(merchant,USDTbalance); // owner gets reimbursed 5$ for initiating swap } } }
Set the URL to perform the GET request on Sends the request
function requestPriceData() public returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); request.add("path", "RAW.ETH.USD.PRICE"); int timesAmount = 10**18; request.addInt("times", timesAmount); return sendChainlinkRequestTo(oracle, request, fee); }
1,815,142
./full_match/3/0x967328588D821b4306fe8F0592faFE94eC930429/sources/contracts/Token5.sol
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, 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"); }
8,243,765
./full_match/4/0x76C5e0C5C9CC41F239B6F50E61f1e374FE1B3a61/sources/contracts/voz.sol
SPDX-License-Identifier: Unlicensed
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); Voz - the next big meme token (exclusively run by the community) }
12,333,512
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // 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"); } /** * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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) { 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; } } /** * @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); } /** * @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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /* * @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; } } /** * @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. */ 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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title The DUSK Provisioner Prestaking Contract. * @author Jules de Smit * @notice This contract will facilitate staking for the DUSK ERC-20 token. */ contract PrestakingProvisioner is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; // The DUSK contract. IERC20 private _token; // Holds all of the information for a staking individual. struct Staker { uint startTime; uint endTime; uint256 amount; uint256 accumulatedReward; uint cooldownTime; uint256 pendingReward; uint256 dailyReward; uint lastUpdated; } mapping(address => Staker) public stakersMap; uint256 public stakersAmount; uint public deactivationTime; modifier onlyStaker() { Staker storage staker = stakersMap[msg.sender]; uint startTime = staker.startTime; require(startTime.add(1 days) <= block.timestamp && startTime != 0, "No stake is active for sender address"); _; } modifier onlyActive() { require(deactivationTime == 0); _; } modifier onlyInactive() { require(deactivationTime != 0); _; } constructor(IERC20 token) public { _token = token; } /** * @notice Ensure nobody can send Ether to this contract, as it is not supposed to have any. */ receive() external payable { revert(); } /** * @notice Deactivate the contract. Only to be used once the campaign * comes to an end. * * NOTE that this sets the contract to inactive indefinitely, and will * not be usable from this point onwards. */ function deactivate() external onlyOwner onlyActive { deactivationTime = block.timestamp; } /** * @notice Can be used by the contract owner to return a user's stake back to them, * without need for going through the withdrawal period. This should only really be used * at the end of the campaign, if a user does not manually withdraw their stake. * @dev This function only works on single addresses, in order to avoid potential * deadlocks caused by high gas requirements. */ function returnStake(address _staker) external onlyOwner { Staker storage staker = stakersMap[_staker]; require(staker.amount > 0, "This person is not staking"); uint comparisonTime = block.timestamp; if (deactivationTime != 0) { comparisonTime = deactivationTime; } distributeRewards(staker, comparisonTime); // If this user has a pending reward, add it to the accumulated reward before // paying him out. staker.accumulatedReward = staker.accumulatedReward.add(staker.pendingReward); removeUser(staker, _staker); } /** * @notice Lock up a given amount of DUSK in the pre-staking contract. * @dev A user is required to approve the amount of DUSK prior to calling this function. */ function stake(uint256 amount) external onlyActive { // Ensure this staker does not exist yet. Staker storage staker = stakersMap[msg.sender]; require(staker.amount == 0, "Address already known"); if (amount > 1000000 ether || amount < 10000 ether) { revert("Amount to stake is out of bounds"); } // Set information for this staker. uint blockTimestamp = block.timestamp; staker.amount = amount; staker.startTime = blockTimestamp; staker.lastUpdated = blockTimestamp; staker.dailyReward = amount.mul(100033).div(100000).sub(amount); stakersAmount++; // Transfer the DUSK to this contract. _token.safeTransferFrom(msg.sender, address(this), amount); } /** * @notice Start the cooldown period for withdrawing a reward. */ function startWithdrawReward() external onlyStaker onlyActive { Staker storage staker = stakersMap[msg.sender]; uint blockTimestamp = block.timestamp; require(staker.cooldownTime == 0, "A withdrawal call has already been triggered"); require(staker.endTime == 0, "Stake already withdrawn"); distributeRewards(staker, blockTimestamp); staker.cooldownTime = blockTimestamp; staker.pendingReward = staker.accumulatedReward; staker.accumulatedReward = 0; } /** * @notice Withdraw the reward. Will only work after the cooldown period has ended. */ function withdrawReward() external onlyStaker { Staker storage staker = stakersMap[msg.sender]; uint cooldownTime = staker.cooldownTime; require(cooldownTime != 0, "The withdrawal cooldown has not been triggered"); if (block.timestamp.sub(cooldownTime) >= 7 days) { uint256 reward = staker.pendingReward; staker.cooldownTime = 0; staker.pendingReward = 0; _token.safeTransfer(msg.sender, reward); } } /** * @notice Start the cooldown period for withdrawing the stake. */ function startWithdrawStake() external onlyStaker onlyActive { Staker storage staker = stakersMap[msg.sender]; uint blockTimestamp = block.timestamp; require(staker.startTime.add(30 days) <= blockTimestamp, "Stakes can only be withdrawn 30 days after initial lock up"); require(staker.endTime == 0, "Stake withdrawal already in progress"); require(staker.cooldownTime == 0, "A withdrawal call has been triggered - please wait for it to complete before withdrawing your stake"); // We distribute the rewards first, so that the withdrawing staker // receives all of their allocated rewards, before setting an `endTime`. distributeRewards(staker, blockTimestamp); staker.endTime = blockTimestamp; } /** * @notice Start the cooldown period for withdrawing the stake. * This function can only be called once the contract is deactivated. * @dev This function is nearly identical to `startWithdrawStake`, * but it was included in order to prevent adding a `SLOAD` call * to `distributeRewards`, making contract usage a bit cheaper during * the campaign. */ function startWithdrawStakeAfterDeactivation() external onlyStaker onlyInactive { Staker storage staker = stakersMap[msg.sender]; uint blockTimestamp = block.timestamp; require(staker.startTime.add(30 days) <= blockTimestamp, "Stakes can only be withdrawn 30 days after initial lock up"); require(staker.endTime == 0, "Stake withdrawal already in progress"); require(staker.cooldownTime == 0, "A withdrawal call has been triggered - please wait for it to complete before withdrawing your stake"); // We distribute the rewards first, so that the withdrawing staker // receives all of their allocated rewards, before setting an `endTime`. distributeRewards(staker, deactivationTime); staker.endTime = blockTimestamp; } /** * @notice Withdraw the stake, and clear the entry of the caller. */ function withdrawStake() external onlyStaker { Staker storage staker = stakersMap[msg.sender]; uint endTime = staker.endTime; require(endTime != 0, "Stake withdrawal call was not yet initiated"); if (block.timestamp.sub(endTime) >= 7 days) { removeUser(staker, msg.sender); } } /** * @notice Update the reward allocation for a given staker. * @param staker The staker to update the reward allocation for. */ function distributeRewards(Staker storage staker, uint comparisonTime) internal { uint numDays = comparisonTime.sub(staker.lastUpdated).div(1 days); if (numDays == 0) { return; } uint256 reward = staker.dailyReward.mul(numDays); staker.accumulatedReward = staker.accumulatedReward.add(reward); staker.lastUpdated = staker.lastUpdated.add(numDays.mul(1 days)); } /** * @notice Remove a user from the staking pool. This ensures proper deletion from * the stakers map and the stakers array, and ensures that all DUSK is returned to * the rightful owner. * @param staker The information of the staker in question * @param sender The address of the staker in question */ function removeUser(Staker storage staker, address sender) internal { uint256 balance = staker.amount.add(staker.accumulatedReward); delete stakersMap[sender]; stakersAmount--; _token.safeTransfer(sender, balance); } }
Start the cooldown period for withdrawing the stake. This function can only be called once the contract is deactivated. This function is nearly identical to `startWithdrawStake`, but it was included in order to prevent adding a `SLOAD` call to `distributeRewards`, making contract usage a bit cheaper during the campaign./ We distribute the rewards first, so that the withdrawing staker receives all of their allocated rewards, before setting an `endTime`.
function startWithdrawStakeAfterDeactivation() external onlyStaker onlyInactive { Staker storage staker = stakersMap[msg.sender]; uint blockTimestamp = block.timestamp; require(staker.startTime.add(30 days) <= blockTimestamp, "Stakes can only be withdrawn 30 days after initial lock up"); require(staker.endTime == 0, "Stake withdrawal already in progress"); require(staker.cooldownTime == 0, "A withdrawal call has been triggered - please wait for it to complete before withdrawing your stake"); distributeRewards(staker, deactivationTime); staker.endTime = blockTimestamp; }
6,901,125
./partial_match/3/0xE333bacb250b1aDC74074d4DBf13662c6Bd96172/sources/GoldenGoose.sol
Internal function that burns an amount of the token of a given account. account The account whose tokens will be burnt. value The amount that will be burnt./
function _burn(address account, uint256 value) internal { require(account != address(0),"Invalid account"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); }
5,077,842
./full_match/42220/0x8E4ce51662Bd78DC7b5bBc61FE87a46210616879/sources/contracts/TimelockController.sol
Checks before execution of an operation's calls./
function _beforeCall(bytes32 predecessor) private view { require(predecessor == bytes32(0) || isOperationDone(predecessor), 'TimelockController: missing dependency'); }
16,351,593
./partial_match/1/0x7733EB6D6F57B53055d748072B94526C3Bd1f6bb/sources/ResidentGenesis.sol
`operator` に権限がある場合は true を返します./
function isApprovedForAll( address owner_, address operator ) public view virtual override(ERC721A, IERC721A) returns (bool) { bool approved = super.isApprovedForAll(owner_, operator); if (address(approvalProxy) != address(0x0)) { return approvalProxy.isApprovedForAll(owner_, operator, approved); } return approved; }
2,777,608
./full_match/77/0x914330F413E95598FE9FA9e2F4d4472c039113ab/sources/contracts/SelectorTokenGasLimiterManager.sol
Tells the token-specific gas limit to be used in the message execution by the AMB bridge on the other network. _selector method selector for the passed message. _token address of the native token that is used in the first argument of handleBridgedTokens/handleNativeTokens. return the gas limit for the message execution./
function requestGasLimit(bytes4 _selector, address _token) public view returns (uint256) { return selectorTokenGasLimit[_selector][_token]; }
5,049,328
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./libraries/UniswapLibrary.sol"; import "./BlockLock.sol"; import "./interfaces/IxTokenManager.sol"; import "./interfaces/IxAsset.sol"; contract xAssetCLR is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, BlockLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // Used to give an identical token representation uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; int24 tickLower; int24 tickUpper; // Prices calculated using above ticks from TickMath.getSqrtRatioAtTick() uint160 priceLower; uint160 priceUpper; int128 lastTwap; // Last stored oracle twap // Max current twap vs last twap deviation percentage divisor (100 = 1%) uint256 maxTwapDeviationDivisor; IERC20 token0; IERC20 token1; uint256 public tokenId; // token id representing this uniswap position uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals) uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals) uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals) uint24 public poolFee; uint8 public token0Decimals; uint8 public token1Decimals; UniswapContracts public uniContracts; IxTokenManager xTokenManager; // xToken manager contract uint32 twapPeriod; struct UniswapContracts { address pool; address router; address quoter; address positionManager; } event Rebalance(); event FeeCollected(uint256 token0Fee, uint256 token1Fee); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, IERC20 _token0, IERC20 _token1, UniswapContracts memory contracts, address _xTokenManagerAddress, uint256 _maxTwapDeviationDivisor, uint8 _token0Decimals, uint8 _token1Decimals ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xAssetCLR", _symbol); tickLower = _tickLower; tickUpper = _tickUpper; priceLower = UniswapLibrary.getSqrtRatio(_tickLower); priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper); token0 = _token0; token1 = _token1; token0Decimals = _token0Decimals; token1Decimals = _token1Decimals; token0DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals); token1DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals); tokenDiffDecimalMultiplier = 10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals))); maxTwapDeviationDivisor = _maxTwapDeviationDivisor; poolFee = 3000; uniContracts = contracts; token0.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token1.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token0.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); token1.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); UniswapLibrary.approveOneInch(token0, token1); xTokenManager = IxTokenManager(_xTokenManagerAddress); lastTwap = getAsset0Price(); twapPeriod = 3600; } /* ========================================================================================= */ /* User-facing */ /* ========================================================================================= */ /** * @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens * @dev amount of the other asset is auto-calculated */ function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); (uint256 amount0, uint256 amount1) = calculateAmountsMintedSingleToken(inputAsset, amount); // Check if address has enough balance uint256 token0Balance = token0.balanceOf(msg.sender); uint256 token1Balance = token1.balanceOf(msg.sender); if (amount0 > token0Balance || amount1 > token1Balance) { amount0 = amount0 > token0Balance ? token0Balance : amount0; amount1 = amount1 > token1Balance ? token1Balance : amount1; (amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1); } token0.safeTransferFrom(msg.sender, address(this), amount0); token1.safeTransferFrom(msg.sender, address(this), amount1); uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); _mintInternal(liquidityAmount); // stake tokens in pool _stake(amount0, amount1); } /** * @dev Burn *amount* of xAssetCLR tokens to receive proportional * amount of pool tokens */ function burn(uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); uint256 totalLiquidity = getTotalLiquidity(); uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply()); super._burn(msg.sender, amount); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(uint128(proRataBalance)); uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE)); uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE)); _unstake(unstakeAmount0, unstakeAmount1); token0.safeTransfer(msg.sender, amount0); token1.safeTransfer(msg.sender, amount1); } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /** * @notice Get Net Asset Value in terms of token 1 * @dev NAV = token 0 amt * token 0 price + token1 amt */ function getNav() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset0Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @notice Get balance in xAssetCLR contract * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getBufferBalance() public view returns (uint256) { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); return getAmountInAsset1Terms(balance0).add(balance1); } /** * @notice Get total balance in the position * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getStakedBalance() public view returns (uint256) { (uint256 amount0, uint256 amount1) = getStakedTokenBalance(); return getAmountInAsset1Terms(amount0).add(amount1); } /** * @notice Get token balances in xAssetCLR contract * @dev returned balances are represented with 18 decimals */ function getBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { return (getBufferToken0Balance(), getBufferToken1Balance()); } /** * @notice Get token0 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken0Balance() public view returns (uint256 amount0) { return getToken0AmountInWei(token0.balanceOf(address(this))); } /** * @notice Get token1 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken1Balance() public view returns (uint256 amount1) { return getToken1AmountInWei(token1.balanceOf(address(this))); } /** * @notice Get token balances in the position * @dev returned balance is represented with 18 decimals */ function getStakedTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity()); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); } /** * @notice Get total liquidity * @dev buffer liquidity + position liquidity */ function getTotalLiquidity() public view returns (uint256 amount) { (uint256 buffer0, uint256 buffer1) = getBufferTokenBalance(); uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1); uint128 positionLiquidity = getPositionLiquidity(); return uint256(bufferLiquidity).add(uint256(positionLiquidity)); } /** * @dev Check how much xAssetCLR tokens will be minted on mint * @dev Uses position liquidity to calculate the amount */ function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount; uint256 previousLiquidity = getTotalLiquidity().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousLiquidity); return mintAmount; } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ /** * @dev Collect rewards from pool and stake them in position * @dev may leave unstaked tokens in contract */ function collectAndRestake() external onlyOwnerOrManager { (uint256 amount0, uint256 amount1) = collect(); (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Collect fees generated from position */ function collect() public onlyOwnerOrManager returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = collectPosition( type(uint128).max, type(uint128).max ); emit FeeCollected(collected0, collected1); } /** * @dev Migrate the current position to a new position with different ticks */ function migratePosition(int24 newTickLower, int24 newTickUpper) public onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT UniswapLibrary.burn(uniContracts.positionManager, tokenId); // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = UniswapLibrary.getSqrtRatio(newTickLower); priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); } /** * @dev Migrate the current position to a new position with different ticks * @dev Migrates position tick lower and upper by same amount of ticks * @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60 * @param ticks how many ticks to shift up or down * @param up whether to move tick range up or down */ function migrateParallel(uint24 ticks, bool up) external onlyOwnerOrManager { require(ticks != 0); int24 newTickLower; int24 newTickUpper; int24 ticksToShift = int24(ticks) * 60; if (up) { newTickLower = tickLower + ticksToShift; newTickUpper = tickUpper + ticksToShift; } else { newTickLower = tickLower - ticksToShift; newTickUpper = tickUpper - ticksToShift; } migratePosition(newTickLower, newTickUpper); } /** * @dev Mint function which initializes the pool position * @dev Must be called before any liquidity can be deposited */ function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0, amount1); token0.safeTransferFrom(msg.sender, address(this), amount0Minted); token1.safeTransferFrom(msg.sender, address(this), amount1Minted); tokenId = createPosition(amount0Minted, amount1Minted); uint256 liquidity = uint256(getLiquidityForAmounts(amount0Minted, amount1Minted)); _mintInternal(liquidity); } /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance() external onlyOwnerOrManager { UniswapLibrary.adminRebalance( UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }) ); emit Rebalance(); } /** * @dev Admin function for staking in position */ function adminStake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Admin function for unstaking from position */ function adminUnstake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _unstake(amount0, amount1); } /** * @dev Admin function for swapping LP tokens in xAssetCLR * @param amount - swap amount (in t0 terms if _0for1 is true, in t1 terms if false) * @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false */ function adminSwap(uint256 amount, bool _0for1) external onlyOwnerOrManager { if (_0for1) { swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } else { swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } } /** * @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - how much output tokens to receive on swap, in 18 decimals * @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false * @param _oneInchData - 1inch calldata, generated off-chain using their v3 api */ function adminSwapOneInch( uint256 minReturn, bool _0for1, bytes memory _oneInchData ) external onlyOwnerOrManager { UniswapLibrary.oneInchSwap( minReturn, _0for1, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), _oneInchData ); } /** * @dev Stake liquidity in position */ function _stake(uint256 amount0, uint256 amount1) private returns (uint256 stakedAmount0, uint256 stakedAmount1) { return UniswapLibrary.stake( amount0, amount1, uniContracts.positionManager, tokenId ); } /** * @dev Unstake liquidity from position */ function _unstake(uint256 amount0, uint256 amount1) private returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount); return collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Withdraws all current liquidity from the position */ function withdrawAll() private returns (uint256 _amount0, uint256 _amount1) { // Collect fees collect(); (_amount0, _amount1) = unstakePosition(getPositionLiquidity()); collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.createPosition( amount0, amount1, uniContracts.positionManager, tokenDetails, positionDetails ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.unstakePosition(liquidity, positionDetails); } function _mintInternal(uint256 _amount) private { uint256 mintAmount = calculateMintAmount(_amount, totalSupply()); return super._mint(msg.sender, mintAmount); } /* * Emergency function in case of errant transfer * of any token directly to contract */ function withdrawToken(address token, address receiver) external onlyOwnerOrManager { require(token != address(token0) && token != address(token1)); uint256 tokenBal = IERC20(address(token)).balanceOf(address(this)); IERC20(address(token)).safeTransfer(receiver, tokenBal); } /** * Mint xAsset tokens using underlying * xAsset contract needs to be approved * @param amount amount to mint * @param isToken0 if true, call mint on token0, else on token1 */ function adminMint(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).mintWithToken(amount); } else { IxAsset(address(token1)).mintWithToken(amount); } } /** * Burn xAsset tokens using underlying * @param amount amount to burn * @param isToken0 if true, call burn on token0, else on token1 */ function adminBurn(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).burn(amount, false, 1); } else { IxAsset(address(token1)).burn(amount, false, 1); } } /** * Approve underlying token to xAsset tokens * @param isToken0 if token 0 is xAsset token, set to true, otherwise false */ function adminApprove(bool isToken0) external onlyOwnerOrManager { if(isToken0) { token1.safeApprove(address(token0), type(uint256).max); } else { token0.safeApprove(address(token1), type(uint256).max); } } function pauseContract() external onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() external onlyOwnerOrManager returns (bool) { _unpause(); return true; } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Function may be called only by owner or manager" ); _; } /* ========================================================================================= */ /* Uniswap helpers */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 0 terms * @param amountOut - amount as output for swap, in token 0 terms */ function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken0ForToken1( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 1 terms * @param amountOut - amount as output for swap, in token 1 terms */ function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken1ForToken0( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition(uint128 amount0, uint128 amount1) private returns (uint256 collected0, uint256 collected1) { return UniswapLibrary.collectPosition( amount0, amount1, tokenId, uniContracts.positionManager ); } /** * @dev Change pool fee and address */ function changePool(address _poolAddress, uint24 _poolFee) external onlyOwnerOrManager { uniContracts.pool = _poolAddress; poolFee = _poolFee; } // Returns the current liquidity in the position function getPositionLiquidity() public view returns (uint128 liquidity) { return UniswapLibrary.getPositionLiquidity( uniContracts.positionManager, tokenId ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price() public view returns (int128) { return UniswapLibrary.getAsset1Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Checks if twap deviates too much from the previous twap */ function checkTwap() private { lastTwap = UniswapLibrary.checkTwap( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier, lastTwap, maxTwapDeviationDivisor ); } /** * @dev Reset last twap if oracle price is consistently above the max deviation */ function resetTwap() external onlyOwnerOrManager { lastTwap = getAsset0Price(); } /** * @dev Set the max twap deviation divisor * @dev if twap moves more than the divisor specified * @dev mint, burn and mintInitial functions are locked */ function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor) external onlyOwnerOrManager { maxTwapDeviationDivisor = newDeviationDivisor; } /** * @dev Set the oracle reading twap period * @dev Twap used is [now - twapPeriod, now] */ function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager { require(newPeriod >= 360); twapPeriod = newPeriod; } /** * @dev Calculates the amounts deposited/withdrawn from the pool * amount0, amount1 - amounts to deposit/withdraw * amount0Minted, amount1Minted - actual amounts which can be deposited */ function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } /** * @dev Calculates single-side minted amount * @param inputAsset - use token0 if 0, token1 else * @param amount - amount to deposit/withdraw */ function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount; if (inputAsset == 0) { liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max); } else { liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount); } (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } function getLiquidityForAmounts(uint256 amount0, uint256 amount1) public view returns (uint128 liquidity) { liquidity = UniswapLibrary.getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, uniContracts.pool ); } function getAmountsForLiquidity(uint128 liquidity) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = UniswapLibrary.getAmountsForLiquidity( liquidity, priceLower, priceUpper, uniContracts.pool ); } /** * @dev Get lower and upper ticks of the pool position */ function getTicks() external view returns (int24 tick0, int24 tick1) { return (tickLower, tickUpper); } /** * Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInWei( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInWei( amount, token1Decimals, token1DecimalMultiplier ); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.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 a proxied contract can't have 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 {UpgradeableProxy-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. */ 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() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @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. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual 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 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 virtual { _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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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) { 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) { // 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) { 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) { 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) { 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) { require(b <= a, "SafeMath: subtraction overflow"); 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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); 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) { require(b > 0, "SafeMath: modulo by zero"); 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) { 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. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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) { 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) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; import "./Utils.sol"; /** * Helper library for Uniswap functions * Used in xAssetCLR */ library UniswapLibrary { using SafeMath for uint256; using SafeERC20 for IERC20; uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // 1inch v3 exchange address address private constant oneInchExchange = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; struct TokenDetails { address token0; address token1; uint256 token0DecimalMultiplier; uint256 token1DecimalMultiplier; uint256 tokenDiffDecimalMultiplier; uint8 token0Decimals; uint8 token1Decimals; } struct PositionDetails { uint24 poolFee; uint32 twapPeriod; uint160 priceLower; uint160 priceUpper; uint256 tokenId; address positionManager; address router; address quoter; address pool; } struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /* ========================================================================================= */ /* Uni V3 Pool Helper functions */ /* ========================================================================================= */ /** * @dev Returns the current pool price in X96 notation */ function getPoolPrice(address _pool) public view returns (uint160) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return sqrtRatioX96; } /** * Get pool price in decimal notation with 12 decimals */ function getPoolPriceWithDecimals(address _pool) public view returns (uint256 price) { uint160 sqrtRatioX96 = getPoolPrice(_pool); return uint256(sqrtRatioX96).mul(uint256(sqrtRatioX96)).mul(1e12) >> 192; } /** * @dev Returns the current pool liquidity */ function getPoolLiquidity(address _pool) public view returns (uint128) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); return pool.liquidity(); } /** * @dev Calculate pool liquidity for given token amounts */ function getLiquidityForAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( getPoolPrice(pool), priceLower, priceUpper, amount0, amount1 ); } /** * @dev Calculate token amounts for given pool liquidity */ function getAmountsForLiquidity( uint128 liquidity, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( getPoolPrice(pool), priceLower, priceUpper, liquidity ); } /** * @dev Calculates the amounts deposited/withdrawn from the pool * @param amount0 - token0 amount to deposit/withdraw * @param amount1 - token1 amount to deposit/withdraw */ function calculatePoolMintedAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, pool ); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount, priceLower, priceUpper, pool ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time IUniswapV3Pool poolImpl = IUniswapV3Pool(pool); uint32 observationTime = getObservationTime(poolImpl); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = poolImpl.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { return ABDKMath64x64.inv( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ) ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset1Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns the earliest oracle observation time */ function getObservationTime(IUniswapV3Pool _pool) public view returns (uint32) { IUniswapV3Pool pool = _pool; (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; } /** * @dev Checks if twap deviates too much from the previous twap * @return current twap */ function checkTwap( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier, int128 lastTwap, uint256 maxTwapDeviationDivisor ) public view returns (int128) { int128 twap = getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); return twap; } /* ========================================================================================= */ /* Uni V3 Swap Router Helper functions */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken0ForToken1( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountOut) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(midPrice).div(1e12); uint256 token0Balance = getBufferToken0Balance( IERC20(tokenDetails.token0), tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); require( token0Balance >= amountIn, "Swap token 0 for token 1: not enough token 0 balance" ); amountIn = getToken0AmountInNativeDecimals( amountIn, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOut = getToken1AmountInNativeDecimals( amountOut, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token0, tokenDetails.token1, positionDetails.poolFee, amountIn, TickMath.MIN_SQRT_RATIO + 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token0, tokenOut: tokenDetails.token1, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1 }) ); return amountOut; } /** * @dev Swap token 1 for token 0 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 1 terms */ function swapToken1ForToken0( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountIn) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(1e12).div(midPrice); uint256 token1Balance = getBufferToken1Balance( IERC20(tokenDetails.token1), tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); require( token1Balance >= amountIn, "Swap token 1 for token 0: not enough token 1 balance" ); amountIn = getToken1AmountInNativeDecimals( amountIn, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOut = getToken0AmountInNativeDecimals( amountOut, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token1, tokenDetails.token0, positionDetails.poolFee, amountIn, TickMath.MAX_SQRT_RATIO - 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token1, tokenOut: tokenDetails.token0, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1 }) ); return amountIn; } /* ========================================================================================= */ /* 1inch Swap Helper functions */ /* ========================================================================================= */ /** * @dev Swap tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - required min amount out from swap, in 18 decimals * @param _0for1 - swap token0 for token1 if true, token1 for token0 if false * @param tokenDetails - xAssetCLR token 0 and token 1 details * @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap */ function oneInchSwap( uint256 minReturn, bool _0for1, TokenDetails memory tokenDetails, bytes memory _oneInchData ) public { uint256 token0AmtSwapped; uint256 token1AmtSwapped; bool success; // inline code to prevent stack too deep errors { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 balanceBeforeToken0 = token0.balanceOf(address(this)); uint256 balanceBeforeToken1 = token1.balanceOf(address(this)); (success, ) = oneInchExchange.call(_oneInchData); require(success, "One inch swap call failed"); uint256 balanceAfterToken0 = token0.balanceOf(address(this)); uint256 balanceAfterToken1 = token1.balanceOf(address(this)); token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0); token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1); } uint256 amountInSwapped; uint256 amountOutReceived; if (_0for1) { amountInSwapped = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOutReceived = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } else { amountInSwapped = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOutReceived = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } // require minimum amount received is > min return require( amountOutReceived > minReturn, "One inch swap not enough output token amount" ); } /** * Approve 1inch v3 for swaps */ function approveOneInch(IERC20 token0, IERC20 token1) public { token0.safeApprove(oneInchExchange, type(uint256).max); token1.safeApprove(oneInchExchange, type(uint256).max); } /* ========================================================================================= */ /* NFT Position Manager Helpers */ /* ========================================================================================= */ /** * @dev Returns the current liquidity in a position represented by tokenId NFT */ function getPositionLiquidity(address positionManager, uint256 tokenId) public view returns (uint128 liquidity) { (, , , , , , , liquidity, , , , ) = INonfungiblePositionManager( positionManager ) .positions(tokenId); } /** * @dev Stake liquidity in position represented by tokenId NFT */ function stake( uint256 amount0, uint256 amount1, address positionManager, uint256 tokenId ) public returns (uint256 stakedAmount0, uint256 stakedAmount1) { (, stakedAmount0, stakedAmount1) = INonfungiblePositionManager( positionManager ) .increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition( uint128 liquidity, PositionDetails memory positionDetails ) public returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(positionDetails.positionManager); (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity( liquidity, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: positionDetails.tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition( uint128 amount0, uint128 amount1, uint256 tokenId, address positionManager ) public returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = INonfungiblePositionManager(positionManager) .collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: amount0, amount1Max: amount1 }) ); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition( uint256 amount0, uint256 amount1, address positionManager, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public returns (uint256 _tokenId) { (_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint( INonfungiblePositionManager.MintParams({ token0: tokenDetails.token0, token1: tokenDetails.token1, fee: positionDetails.poolFee, tickLower: getTickFromPrice(positionDetails.priceLower), tickUpper: getTickFromPrice(positionDetails.priceUpper), amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); } /** * @dev burn NFT representing a pool position with tokenId * @dev uses NFT Position Manager */ function burn(address positionManager, uint256 tokenId) public { INonfungiblePositionManager(positionManager).burn(tokenId); } /* ========================================================================================= */ /* xAssetCLR Helpers */ /* ========================================================================================= */ /** * @notice Admin function to stake tokens * @dev used in case there's leftover tokens in the contract * @dev Function differs from adminStake in that * @dev it calculates token amounts to stake so as to have * @dev all or most of the tokens in the position, and * @dev no tokens in buffer balance ; swaps as necessary */ function adminRebalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public { (uint256 token0Balance, uint256 token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); (uint256 stakeAmount0, uint256 stakeAmount1) = checkIfAmountsMatchAndSwap( token0Balance, token1Balance, positionDetails, tokenDetails ); (token0Balance, token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); if (stakeAmount0 > token0Balance) { stakeAmount0 = token0Balance; } if (stakeAmount1 > token1Balance) { stakeAmount1 = token1Balance; } (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts( stakeAmount0, stakeAmount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); require( amount0 != 0 || amount1 != 0, "Rebalance amounts are 0" ); stake( amount0, amount1, positionDetails.positionManager, positionDetails.tokenId ); } /** * @dev Check if token amounts match before attempting rebalance in xAssetCLR * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible * @param amount0ToMint how much token0 amount we want to deposit/withdraw * @param amount1ToMint how much token1 amount we want to deposit/withdraw */ function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio = // minted liquidity / total pool liquidity // used to calculate swap impact in pool uint256 mintLiquidity = getLiquidityForAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( liquidityRatio, AmountsMinted({ amount0ToMint: amount0ToMint, amount1ToMint: amount1ToMint, amount0Minted: amount0Minted, amount1Minted: amount1Minted }), tokenDetails, positionDetails ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } } /** * @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for * @dev depositing/withdrawing liquidity to/from Uniswap pool */ function restoreTokenRatios( int128 liquidityRatio, AmountsMinted memory amountsMinted, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private returns (uint256 amount0, uint256 amount1) { // after normalization, returned swap amount will be in wei representation uint256 swapAmount; { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap amount returned is always in asset 0 terms swapAmount = Utils.calculateSwapAmount( Utils.AmountsMinted({ amount0ToMint: getToken0AmountInWei( amountsMinted.amount0ToMint, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1ToMint: getToken1AmountInWei( amountsMinted.amount1ToMint, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), amount0Minted: getToken0AmountInWei( amountsMinted.amount0Minted, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1Minted: getToken1AmountInWei( amountsMinted.amount1Minted, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) }), liquidityRatio, midPrice ); if (swapAmount == 0) { return ( amountsMinted.amount0ToMint, amountsMinted.amount1ToMint ); } } uint256 swapAmountWithSlippage = swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)); uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); (uint256 balance0, uint256 balance1) = getBufferTokenBalance(tokenDetails); if (mul1 > mul2) { if (balance0 < swapAmountWithSlippage) { swapAmountWithSlippage = balance0; } // Swap tokens uint256 amountOut = swapToken0ForToken1( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.sub( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountOut is already in native decimals amount1 = amountsMinted.amount1ToMint.add(amountOut); } else if (mul1 < mul2) { balance1 = getAmountInAsset0Terms( balance1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); if (balance1 < swapAmountWithSlippage) { swapAmountWithSlippage = balance1; } uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap tokens uint256 amountIn = swapToken1ForToken0( swapAmountWithSlippage.mul(midPrice).div(1e12), swapAmount.mul(midPrice).div(1e12), positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.add( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountIn is already in native decimals amount1 = amountsMinted.amount1ToMint.sub(amountIn); } } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance(TokenDetails memory tokenDetails) public view returns (uint256 amount0, uint256 amount1) { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); return ( getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance( IERC20 token0, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public view returns (uint256 amount0) { return getToken0AmountInWei( token0.balanceOf(address(this)), token0Decimals, token0DecimalMultiplier ); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance( IERC20 token1, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public view returns (uint256 amount1) { return getToken1AmountInWei( token1.balanceOf(address(this)), token1Decimals, token1DecimalMultiplier ); } /* ========================================================================================= */ /* Miscellaneous */ /* ========================================================================================= */ /** * @dev Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token1DecimalMultiplier); } return amount; } /** * @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token1DecimalMultiplier); } return amount; } /** * @dev get price from tick */ function getSqrtRatio(int24 tick) public pure returns (uint160) { return TickMath.getSqrtRatioAtTick(tick); } /** * @dev get tick from price */ function getTickFromPrice(uint160 price) public pure returns (int24) { return TickMath.getTickAtSqrtRatio(price); } /** * @dev Subtract two numbers and return absolute value */ function subAbs(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; function lock(address _address) internal { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } modifier notLocked(address lockedAddress) { require( lastLockedBlock[lockedAddress] <= block.number, "Address is temporarily locked" ); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Minimal xAsset interface * Only mintWithToken and burn functions */ interface IxAsset is IERC20 { /* * @dev Mint xAsset using Asset * @notice Must run ERC20 approval first * @param amount: Asset amount to contribute */ function mintWithToken(uint256 amount) external; /* * @dev Burn xAsset tokens * @notice Will fail if redemption value exceeds available liquidity * @param amount: xAsset amount to redeem * @param redeemForEth: if true, redeem xAsset for ETH * @param minRate: Kyber.getExpectedRate xAsset=>ETH if redeemForEth true (no-op if false) */ function burn(uint256 amount, bool redeemForEth, uint256 minRate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // 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"); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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 SafeMathUpgradeable { /** * @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) { 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) { 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) { // 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) { 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) { 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) { 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) { require(b <= a, "SafeMath: subtraction overflow"); 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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); 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) { require(b > 0, "SafeMath: modulo by zero"); 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) { 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. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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) { 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) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // 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"); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected].com> */ pragma solidity 0.7.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(uint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) internal pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) internal pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; /** * Library with utility functions for xAssetCLR */ library Utils { using SafeMath for uint256; struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /** Get asset 1 twap price for the period of [now - secondsAgo, now] */ function getTWAP(int56[] memory prices, uint32 secondsAgo) internal pure returns (int128) { // Formula is // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo require(secondsAgo != 0, "Cannot get twap for 0 seconds"); int256 diff = int256(prices[1]) - int256(prices[0]); uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff); int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo)); int128 twap = ABDKMath64x64.pow( ABDKMath64x64.divu(10001, 10000), uint256(ABDKMath64x64.toUInt(fraction)) ); // This is necessary because we cannot call .pow on unsigned integers // And thus when asset0Price > asset1Price we need to reverse the value twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap; return twap; } /** * Helper function to calculate how much to swap when * staking or withdrawing from Uni V3 Pools * Goal of this function is to calibrate the staking tokens amounts * When we want to stake, for example, 100 token0 and 10 token1 * But pool price demands 100 token0 and 40 token1 * We cannot directly stake 100 t0 and 10 t1, so we swap enough * to be able to stake the value of 100 t0 and 10 t1 */ function calculateSwapAmount( AmountsMinted memory amountsMinted, int128 liquidityRatio, uint256 midPrice ) internal pure returns (uint256 swapAmount) { // formula is more complicated than xU3LP case // it includes the asset prices, and considers the swap impact on the pool // base formula is this: // n - swap amt, x - amount 0 to mint, y - amount 1 to mint, // z - amount 0 minted, t - amount 1 minted, p0 - pool mid price // l - liquidity ratio (current mint liquidity vs total pool liq) // (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) -> // n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T) uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); uint256 sub = subAbs(mul1, mul2); uint256 add1 = ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint); uint256 add2 = midPrice .mul( ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint) ) .div(1e12); uint256 add3 = midPrice.mul(amountsMinted.amount0Minted).div(1e12); uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted); // Some numbers are too big to fit in ABDK's div 128-bit representation // So calculate the root of the equation and then raise to the 2nd power int128 nRatio = ABDKMath64x64.divu( ABDKMath64x64.sqrtu(sub), ABDKMath64x64.sqrtu(add) ); int64 n = ABDKMath64x64.toInt(nRatio); swapAmount = uint256(n)**2; } // comparator for 32-bit timestamps // @return bool Whether a <= b function lte( uint32 time, uint32 a, uint32 b ) internal pure returns (bool) { if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } // Subtract two numbers and return absolute value function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 tokenId); /** * @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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../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; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
Returns amount in terms of asset 1 amount asset 0 price/
function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); }
1,686,579
// SPDX-License-Identifier: MIT pragma solidity >=0.8.11 <0.9.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; contract Marketplace is OwnableUpgradeable, ReentrancyGuardUpgradeable { /// @notice Types of offer enum Types { regular, auction } /// @notice Bid object struct Bid { address payable buyer; uint256 amount; bool isWinner; bool isChargedBack; } /// @notice Lot object struct Lot { address nft; address payable seller; uint256 tokenId; Types offerType; uint256 price; uint256 stopPrice; uint256 auctionStart; uint256 auctionEnd; bool isSold; bool isCanceled; } /// @notice This multiplier allows us to use the fractional part for the commission uint256 private constant FEES_MULTIPLIER = 10000; /// @notice Marketplace fee /// @dev 1 == 0.01% uint256 public serviceFee; /// @notice Address that will receive marketplace fees address payable public feesCollector; /// @notice Users who are not allowed to the marketplace mapping(address => bool) public banList; /// @notice All lots IDs of the seller /// @dev Current and past lots mapping(address => uint256[]) private lotsOfSeller; /// @notice All bids of lot mapping(uint256 => Bid[]) public bidsOfLot; /// @notice Array of lots Lot[] public lots; /// @notice Events event ServiceFeeChanged(uint256 newFee); event UserBanStatusChanged(address user, bool isBanned); event TokenRemovedFromSale(uint256 lotId, bool removedBySeller); event Sold(uint256 lotId, address buyer, uint256 price, uint256 fee); event RegularLotCreated(uint256 lotId, address seller); event AuctionLotCreated(uint256 lotId, address seller); event FailedTx(uint256 lotId, uint256 bidId, address recipient, uint256 amount); /// @notice Acts like constructor() for upgradeable contracts function initialize() public initializer { __Ownable_init(); __ReentrancyGuard_init(); feesCollector = payable(msg.sender); serviceFee = 100; } /// @notice Allow this contract to receive ether receive() external payable {} /** * @notice Checks that the user is not banned */ modifier notBanned() { require(!banList[msg.sender], "you are banned"); _; } /** * @notice Checks that the lot has not been sold or canceled * @param lotId - ID of the lot */ modifier lotIsActive(uint256 lotId) { Lot memory lot = lots[lotId]; require(!lot.isSold, "lot already sold"); require(!lot.isCanceled, "lot canceled"); _; } /** * @notice Get filtered lots * @param from - Minimal lotId * @param to - Get to lot Id. 0 ar any value greater than lots.length will set "to" to lots.length * @param getActive - Is get active lots? * @param getSold - Is get sold lots? * @param getCanceled - Is get canceled lots? * @return _filteredLots - Array of filtered lots */ function getLots( uint256 from, uint256 to, bool getActive, bool getSold, bool getCanceled ) external view returns (Lot[] memory _filteredLots) { require(from < lots.length, "value is bigger than lots count"); if (to == 0 || to >= lots.length) to = lots.length - 1; Lot[] memory _tempLots = new Lot[](lots.length); uint256 _count = 0; for (uint256 i = from; i <= to; i++) { if ( (getActive && (!lots[i].isSold && !lots[i].isCanceled)) || (getSold && lots[i].isSold) || (getCanceled && lots[i].isCanceled) ) { _tempLots[_count] = lots[i]; _count++; } } _filteredLots = new Lot[](_count); for (uint256 i = 0; i < _count; i++) { _filteredLots[i] = _tempLots[i]; } } /** * @notice Get all lots of the seller * @param seller - Address of seller * @return array of lot IDs */ function getLotsOfSeller(address seller) external view returns (uint256[] memory) { return lotsOfSeller[seller]; } /** * @notice Get all bids of the lot * @param lotId - ID of lot * @return array of lot IDs */ function getBidsOfLot(uint256 lotId) external view returns (Bid[] memory) { return bidsOfLot[lotId]; } /** * @notice Get lot by ERC721 address and token ID * @param nft - Address of ERC721 token * @param tokenId - ID of the token * @return _isFound - Is found or not * @return _lotId - ID of the lot */ function getLotId(address nft, uint256 tokenId) external view returns (bool _isFound, uint256 _lotId) { require(nft != address(0), "zero_addr"); _isFound = false; _lotId = 0; for (uint256 i; i < lots.length; i++) { if (lots[i].nft == nft && lots[i].tokenId == tokenId) { _isFound = true; _lotId = i; break; } } } /** * @notice Get bids of the user by lot Id * @param bidder - User's address * @param lotId - ID of lot * @return _bid - Return bid */ function getBidsOf(address bidder, uint256 lotId) external view returns (Bid memory _bid) { for (uint256 i = 0; i < bidsOfLot[lotId].length; i++) { _bid = bidsOfLot[lotId][i]; if (_bid.buyer == bidder && !_bid.isChargedBack) { return _bid; } } revert("bid not found"); } /** * @notice Change marketplace fee * @param newServiceFee - New fee amount */ function setServiceFee(uint256 newServiceFee) external onlyOwner { require(serviceFee != newServiceFee, "similar amount"); serviceFee = newServiceFee; emit ServiceFeeChanged(newServiceFee); } /** * @notice Change user's ban status * @param user - Address of account * @param isBanned - Status of account */ function setBanStatus(address user, bool isBanned) external onlyOwner { require(banList[user] != isBanned, "address already have this status"); banList[user] = isBanned; emit UserBanStatusChanged(user, isBanned); } /** * @notice Remove lot from sale and return users funds * @dev Only lot owner or contract owner can do this * @param lotId - ID of the lot */ function removeLot(uint256 lotId) external lotIsActive(lotId) nonReentrant { Lot storage lot = lots[lotId]; require(msg.sender == lot.seller || msg.sender == owner(), "only owner or seller can remove"); lot.isCanceled = true; if (lot.offerType == Types.auction) { // send funds to bidders Bid[] storage bids = bidsOfLot[lotId]; for (uint256 i = 0; i < bids.length; i++) { Bid storage _bid = bids[i]; if (!_bid.isChargedBack && !_bid.isWinner) { _bid.isChargedBack = true; (bool sent, ) = _bid.buyer.call{value: _bid.amount}(""); require(sent, "something went wrong"); } } } // send NFT back to the seller IERC721Upgradeable(lot.nft).safeTransferFrom(address(this), lot.seller, lot.tokenId); emit TokenRemovedFromSale(lotId, msg.sender == lot.seller); } /** * @notice Update price for a regular offer * @param lotId - ID of the lot * @param newPrice - New price of the lot */ function changeRegularOfferPrice(uint256 lotId, uint256 newPrice) external lotIsActive(lotId) { Lot storage _lot = lots[lotId]; require(msg.sender == _lot.seller, "not seller"); require(_lot.offerType == Types.regular, "only regular offer"); require(_lot.price != newPrice, "same"); _lot.price = newPrice; } /** * @notice Buy regular lot (not auction) * @param lotId - ID of the lot */ function buy(uint256 lotId) external payable notBanned lotIsActive(lotId) nonReentrant { Lot storage lot = lots[lotId]; require(lot.offerType == Types.regular, "only regular lot type"); require(msg.value == lot.price, "wrong ether amount"); _buy(lot, lot.price, lotId); } /** * @notice Make auction bid * @param lotId - ID of the lot */ function bid(uint256 lotId) external payable notBanned lotIsActive(lotId) nonReentrant { Lot storage lot = lots[lotId]; require(lot.offerType == Types.auction, "only auction lot type"); require(lot.auctionStart <= block.timestamp, "auction is not started yet"); require(lot.auctionEnd >= block.timestamp, "auction already finished"); Bid[] storage bids = bidsOfLot[lotId]; uint256 bidAmount = msg.value; for (uint256 i = 0; i < bids.length; i++) { if (bids[i].buyer == msg.sender && !bids[i].isChargedBack) { bidAmount += bids[i].amount; } } require(bidAmount <= lot.stopPrice, "amount should be less or equal to stop price"); require(bidAmount >= lot.price, "amount should be great or equal to lot price"); if (bids.length > 0) { require(bids[bids.length - 1].amount < bidAmount, "bid should be greater than last"); } // Pay (bool fundsInMarketplace, ) = payable(address(this)).call{value: msg.value}(""); require(fundsInMarketplace, "payment error (bidder)"); Bid memory newBid = Bid(payable(msg.sender), bidAmount, false, false); // Do not send funds to previous bids, because this amount in last bid for (uint256 i = 0; i < bids.length; i++) { if (bids[i].buyer == msg.sender && !bids[i].isChargedBack) { bids[i].isChargedBack = true; } } bids.push(newBid); // finalize when target price reached if (bidAmount == lot.stopPrice) { lot.auctionEnd = block.timestamp - 1; _finalize(lotId); } } /** * @notice Finalize auction (external function) * @param lotId - ID of the lot */ function finalize(uint256 lotId) external payable notBanned lotIsActive(lotId) nonReentrant { _finalize(lotId); } /** * @notice Finalize auction (internal function) * @param lotId - ID of the lot */ function _finalize(uint256 lotId) internal { Lot storage lot = lots[lotId]; Bid[] storage bids = bidsOfLot[lotId]; require(bids.length > 0, "no bids"); require(lot.auctionEnd < block.timestamp, "auction is not finished yet"); uint256 winnerId; if (bids.length == 1) { winnerId = 0; } else { winnerId = bids.length - 1; for (uint256 i = 0; i < bids.length - 1; i++) { Bid storage _bid = bids[i]; if (!_bid.isChargedBack) { _bid.isChargedBack = true; (bool success, ) = _bid.buyer.call{value: _bid.amount}(""); if (!success) { emit FailedTx(lotId, i, _bid.buyer, _bid.amount); } } } } bids[winnerId].isWinner = true; _buy(lot, bids[winnerId].amount, lotId); } /** * @notice Send funds and token * @param lot - Lot to buy * @param price - Lot price * @param lotId - ID of the lot */ function _buy( Lot storage lot, uint256 price, uint256 lotId ) internal { uint256 fee = (price * serviceFee) / FEES_MULTIPLIER; (bool payedToSeller, ) = lot.seller.call{value: price - fee}(""); require(payedToSeller, "payment error (seller)"); (bool payedToFeesCollector, ) = feesCollector.call{value: fee}(""); require(payedToFeesCollector, "payment error (fees collector)"); lot.isSold = true; IERC721Upgradeable(lot.nft).safeTransferFrom(address(this), msg.sender, lot.tokenId); emit Sold(lotId, msg.sender, price, fee); } /** * @notice Regular offer (not auction) * @param nft - Address of NFT contract * @param tokenId - ID of token to sale * @param price - Token price * @return _lotId - Lot ID */ function makeRegularOffer( address nft, uint256 tokenId, uint256 price ) external notBanned returns (uint256 _lotId) { require(nft != address(0), "zero address for NFT"); require(price > 0, "price should be greater than 0"); IERC721Upgradeable(nft).safeTransferFrom(msg.sender, address(this), tokenId); Lot memory newLot = Lot(nft, payable(msg.sender), tokenId, Types.regular, price, 0, 0, 0, false, false); lots.push(newLot); _lotId = lots.length - 1; lotsOfSeller[msg.sender].push(_lotId); emit RegularLotCreated(_lotId, msg.sender); } /** * @notice Regular offer (not auction) * @param nft - Address of NFT contract * @param tokenId - ID of token to sale * @param price - Token price * @param stopPrice - Price to stop auction and sale immediately * @param auctionStart - Auction starts at * @param auctionEnd - Auction finish at * @return _lotId - Lot ID */ function makeAuctionOffer( address nft, uint256 tokenId, uint256 price, uint256 stopPrice, uint256 auctionStart, uint256 auctionEnd ) external notBanned returns (uint256 _lotId) { require(nft != address(0), "zero address"); require(auctionStart > 0, "auction start time should be greater than 0"); require(auctionEnd > auctionStart, "auction end time should be greater than auction start time"); require(price > 0, "price should be greater than 0"); require(stopPrice > price, "stop price should be greater than price"); IERC721Upgradeable(nft).safeTransferFrom(msg.sender, address(this), tokenId); Lot memory newLot = Lot( nft, payable(msg.sender), tokenId, Types.auction, price, stopPrice, auctionStart, auctionEnd, false, false ); lots.push(newLot); _lotId = lots.length - 1; lotsOfSeller[msg.sender].push(_lotId); emit AuctionLotCreated(_lotId, msg.sender); } /// @notice To make ERC721 safeTransferFrom works function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data ) external pure returns (bytes4) { return IERC721ReceiverUpgradeable.onERC721Received.selector; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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; } // 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 IERC721ReceiverUpgradeable { /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // 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 // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // 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 IERC165Upgradeable { /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.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 !AddressUpgradeable.isContract(address(this)); } } // 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 AddressUpgradeable { /** * @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 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); } } } }
Change marketplace fee newServiceFee - New fee amount/
function setServiceFee(uint256 newServiceFee) external onlyOwner { require(serviceFee != newServiceFee, "similar amount"); serviceFee = newServiceFee; emit ServiceFeeChanged(newServiceFee); }
1,354,886
pragma solidity ^0.4.25; contract IStdToken { function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns(bool); } contract EtheramaCommon { //main adrministrators of the Etherama network mapping(address => bool) private _administrators; //main managers of the Etherama network mapping(address => bool) private _managers; modifier onlyAdministrator() { require(_administrators[msg.sender]); _; } modifier onlyAdministratorOrManager() { require(_administrators[msg.sender] || _managers[msg.sender]); _; } constructor() public { _administrators[msg.sender] = true; } function addAdministator(address addr) onlyAdministrator public { _administrators[addr] = true; } function removeAdministator(address addr) onlyAdministrator public { _administrators[addr] = false; } function isAdministrator(address addr) public view returns (bool) { return _administrators[addr]; } function addManager(address addr) onlyAdministrator public { _managers[addr] = true; } function removeManager(address addr) onlyAdministrator public { _managers[addr] = false; } function isManager(address addr) public view returns (bool) { return _managers[addr]; } } contract EtheramaGasPriceLimit is EtheramaCommon { uint256 public MAX_GAS_PRICE = 0 wei; event onSetMaxGasPrice(uint256 val); //max gas price modifier for buy/sell transactions in order to avoid a "front runner" vulnerability. //It is applied to all network contracts modifier validGasPrice(uint256 val) { require(val > 0); _; } constructor(uint256 maxGasPrice) public validGasPrice(maxGasPrice) { setMaxGasPrice(maxGasPrice); } //only main administators or managers can set max gas price function setMaxGasPrice(uint256 val) public validGasPrice(val) onlyAdministratorOrManager { MAX_GAS_PRICE = val; emit onSetMaxGasPrice(val); } } // Core contract for Etherama network contract EtheramaCore is EtheramaGasPriceLimit { uint256 constant public MAGNITUDE = 2**64; // Max and min amount of tokens which can be bought or sold. There are such limits because of math precision uint256 constant public MIN_TOKEN_DEAL_VAL = 0.1 ether; uint256 constant public MAX_TOKEN_DEAL_VAL = 1000000 ether; // same same for ETH uint256 constant public MIN_ETH_DEAL_VAL = 0.001 ether; uint256 constant public MAX_ETH_DEAL_VAL = 200000 ether; // percent of a transaction commission which is taken for Big Promo bonus uint256 public _bigPromoPercent = 5 ether; // percent of a transaction commission which is taken for Quick Promo bonus uint256 public _quickPromoPercent = 5 ether; // percent of a transaction commission which is taken for Etherama DEV team uint256 public _devRewardPercent = 15 ether; // percent of a transaction commission which is taken for Token Owner. uint256 public _tokenOwnerRewardPercent = 30 ether; // percent of a transaction commission which is taken for share reward. Each token holder receives a small reward from each buy or sell transaction proportionally his holding. uint256 public _shareRewardPercent = 25 ether; // percent of a transaction commission which is taken for a feraral link owner. If there is no any referal then this part of commission goes to share reward. uint256 public _refBonusPercent = 20 ether; // interval of blocks for Big Promo bonus. It means that a user which buy a bunch of tokens for X ETH in that particular block will receive a special bonus uint128 public _bigPromoBlockInterval = 9999; // same same for Quick Promo uint128 public _quickPromoBlockInterval = 100; // minimum eth amount of a purchase which is required to participate in promo. uint256 public _promoMinPurchaseEth = 1 ether; // minimum eth purchase which is required to get a referal link. uint256 public _minRefEthPurchase = 0.5 ether; // percent of fee which is supposed to distribute. uint256 public _totalIncomeFeePercent = 100 ether; // current collected big promo bonus uint256 public _currentBigPromoBonus; // current collected quick promo bonus uint256 public _currentQuickPromoBonus; uint256 public _devReward; uint256 public _initBlockNum; mapping(address => bool) private _controllerContracts; mapping(uint256 => address) private _controllerIndexer; uint256 private _controllerContractCount; //user token balances per data contracts mapping(address => mapping(address => uint256)) private _userTokenLocalBalances; //user reward payouts per data contracts mapping(address => mapping(address => uint256)) private _rewardPayouts; //user ref rewards per data contracts mapping(address => mapping(address => uint256)) private _refBalances; //user won quick promo bonuses per data contracts mapping(address => mapping(address => uint256)) private _promoQuickBonuses; //user won big promo bonuses per data contracts mapping(address => mapping(address => uint256)) private _promoBigBonuses; //user saldo between buys and sels in eth per data contracts mapping(address => mapping(address => uint256)) private _userEthVolumeSaldos; //bonuses per share per data contracts mapping(address => uint256) private _bonusesPerShare; //buy counts per data contracts mapping(address => uint256) private _buyCounts; //sell counts per data contracts mapping(address => uint256) private _sellCounts; //total volume eth per data contracts mapping(address => uint256) private _totalVolumeEth; //total volume tokens per data contracts mapping(address => uint256) private _totalVolumeToken; event onWithdrawUserBonus(address indexed userAddress, uint256 ethWithdrawn); modifier onlyController() { require(_controllerContracts[msg.sender]); _; } constructor(uint256 maxGasPrice) EtheramaGasPriceLimit(maxGasPrice) public { _initBlockNum = block.number; } function getInitBlockNum() public view returns (uint256) { return _initBlockNum; } function addControllerContract(address addr) onlyAdministrator public { _controllerContracts[addr] = true; _controllerIndexer[_controllerContractCount] = addr; _controllerContractCount = SafeMath.add(_controllerContractCount, 1); } function removeControllerContract(address addr) onlyAdministrator public { _controllerContracts[addr] = false; } function changeControllerContract(address oldAddr, address newAddress) onlyAdministrator public { _controllerContracts[oldAddr] = false; _controllerContracts[newAddress] = true; } function setBigPromoInterval(uint128 val) onlyAdministrator public { _bigPromoBlockInterval = val; } function setQuickPromoInterval(uint128 val) onlyAdministrator public { _quickPromoBlockInterval = val; } function addBigPromoBonus() onlyController payable public { _currentBigPromoBonus = SafeMath.add(_currentBigPromoBonus, msg.value); } function addQuickPromoBonus() onlyController payable public { _currentQuickPromoBonus = SafeMath.add(_currentQuickPromoBonus, msg.value); } function setPromoMinPurchaseEth(uint256 val) onlyAdministrator public { _promoMinPurchaseEth = val; } function setMinRefEthPurchase(uint256 val) onlyAdministrator public { _minRefEthPurchase = val; } function setTotalIncomeFeePercent(uint256 val) onlyController public { require(val > 0 && val <= 100 ether); _totalIncomeFeePercent = val; } // set reward persentages of buy/sell fee. Token owner cannot take more than 40%. function setRewardPercentages(uint256 tokenOwnerRewardPercent, uint256 shareRewardPercent, uint256 refBonusPercent, uint256 bigPromoPercent, uint256 quickPromoPercent) onlyAdministrator public { require(tokenOwnerRewardPercent <= 40 ether); require(shareRewardPercent <= 100 ether); require(refBonusPercent <= 100 ether); require(bigPromoPercent <= 100 ether); require(quickPromoPercent <= 100 ether); require(tokenOwnerRewardPercent + shareRewardPercent + refBonusPercent + _devRewardPercent + _bigPromoPercent + _quickPromoPercent == 100 ether); _tokenOwnerRewardPercent = tokenOwnerRewardPercent; _shareRewardPercent = shareRewardPercent; _refBonusPercent = refBonusPercent; _bigPromoPercent = bigPromoPercent; _quickPromoPercent = quickPromoPercent; } function payoutQuickBonus(address userAddress) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _promoQuickBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _currentQuickPromoBonus); _currentQuickPromoBonus = 0; } function payoutBigBonus(address userAddress) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _promoBigBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoBigBonuses[dataContractAddress][userAddress], _currentBigPromoBonus); _currentBigPromoBonus = 0; } function addDevReward() onlyController payable public { _devReward = SafeMath.add(_devReward, msg.value); } function withdrawDevReward() onlyAdministrator public { uint256 reward = _devReward; _devReward = 0; msg.sender.transfer(reward); } function getBlockNumSinceInit() public view returns(uint256) { return block.number - getInitBlockNum(); } function getQuickPromoRemainingBlocks() public view returns(uint256) { uint256 d = getBlockNumSinceInit() % _quickPromoBlockInterval; d = d == 0 ? _quickPromoBlockInterval : d; return _quickPromoBlockInterval - d; } function getBigPromoRemainingBlocks() public view returns(uint256) { uint256 d = getBlockNumSinceInit() % _bigPromoBlockInterval; d = d == 0 ? _bigPromoBlockInterval : d; return _bigPromoBlockInterval - d; } function getBonusPerShare(address dataContractAddress) public view returns(uint256) { return _bonusesPerShare[dataContractAddress]; } function getTotalBonusPerShare() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _bonusesPerShare[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function addBonusPerShare() onlyController payable public { EtheramaData data = Etherama(msg.sender)._data(); uint256 shareBonus = (msg.value * MAGNITUDE) / data.getTotalTokenSold(); _bonusesPerShare[address(data)] = SafeMath.add(_bonusesPerShare[address(data)], shareBonus); } function getUserRefBalance(address dataContractAddress, address userAddress) public view returns(uint256) { return _refBalances[dataContractAddress][userAddress]; } function getUserRewardPayouts(address dataContractAddress, address userAddress) public view returns(uint256) { return _rewardPayouts[dataContractAddress][userAddress]; } function resetUserRefBalance(address userAddress) onlyController public { resetUserRefBalance(Etherama(msg.sender).getDataContractAddress(), userAddress); } function resetUserRefBalance(address dataContractAddress, address userAddress) internal { _refBalances[dataContractAddress][userAddress] = 0; } function addUserRefBalance(address userAddress) onlyController payable public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _refBalances[dataContractAddress][userAddress] = SafeMath.add(_refBalances[dataContractAddress][userAddress], msg.value); } function addUserRewardPayouts(address userAddress, uint256 val) onlyController public { addUserRewardPayouts(Etherama(msg.sender).getDataContractAddress(), userAddress, val); } function addUserRewardPayouts(address dataContractAddress, address userAddress, uint256 val) internal { _rewardPayouts[dataContractAddress][userAddress] = SafeMath.add(_rewardPayouts[dataContractAddress][userAddress], val); } function resetUserPromoBonus(address userAddress) onlyController public { resetUserPromoBonus(Etherama(msg.sender).getDataContractAddress(), userAddress); } function resetUserPromoBonus(address dataContractAddress, address userAddress) internal { _promoQuickBonuses[dataContractAddress][userAddress] = 0; _promoBigBonuses[dataContractAddress][userAddress] = 0; } function trackBuy(address userAddress, uint256 volEth, uint256 volToken) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _buyCounts[dataContractAddress] = SafeMath.add(_buyCounts[dataContractAddress], 1); _userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.add(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth); trackTotalVolume(dataContractAddress, volEth, volToken); } function trackSell(address userAddress, uint256 volEth, uint256 volToken) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _sellCounts[dataContractAddress] = SafeMath.add(_sellCounts[dataContractAddress], 1); _userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.sub(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth); trackTotalVolume(dataContractAddress, volEth, volToken); } function trackTotalVolume(address dataContractAddress, uint256 volEth, uint256 volToken) internal { _totalVolumeEth[dataContractAddress] = SafeMath.add(_totalVolumeEth[dataContractAddress], volEth); _totalVolumeToken[dataContractAddress] = SafeMath.add(_totalVolumeToken[dataContractAddress], volToken); } function getBuyCount(address dataContractAddress) public view returns (uint256) { return _buyCounts[dataContractAddress]; } function getTotalBuyCount() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _buyCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function getSellCount(address dataContractAddress) public view returns (uint256) { return _sellCounts[dataContractAddress]; } function getTotalSellCount() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _sellCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function getTotalVolumeEth(address dataContractAddress) public view returns (uint256) { return _totalVolumeEth[dataContractAddress]; } function getTotalVolumeToken(address dataContractAddress) public view returns (uint256) { return _totalVolumeToken[dataContractAddress]; } function getUserEthVolumeSaldo(address dataContractAddress, address userAddress) public view returns (uint256) { return _userEthVolumeSaldos[dataContractAddress][userAddress]; } function getUserTotalEthVolumeSaldo(address userAddress) public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _userEthVolumeSaldos[Etherama(_controllerIndexer[i]).getDataContractAddress()][userAddress]); } } function getTotalCollectedPromoBonus() public view returns (uint256) { return SafeMath.add(_currentBigPromoBonus, _currentQuickPromoBonus); } function getUserTotalPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _promoBigBonuses[dataContractAddress][userAddress]); } function getUserQuickPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return _promoQuickBonuses[dataContractAddress][userAddress]; } function getUserBigPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return _promoBigBonuses[dataContractAddress][userAddress]; } function getUserTokenLocalBalance(address dataContractAddress, address userAddress) public view returns(uint256) { return _userTokenLocalBalances[dataContractAddress][userAddress]; } function addUserTokenLocalBalance(address userAddress, uint256 val) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.add(_userTokenLocalBalances[dataContractAddress][userAddress], val); } function subUserTokenLocalBalance(address userAddress, uint256 val) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.sub(_userTokenLocalBalances[dataContractAddress][userAddress], val); } function getUserReward(address dataContractAddress, address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 reward) { EtheramaData data = EtheramaData(dataContractAddress); if (incShareBonus) { reward = data.getBonusPerShare() * data.getActualUserTokenBalance(userAddress); reward = ((reward < data.getUserRewardPayouts(userAddress)) ? 0 : SafeMath.sub(reward, data.getUserRewardPayouts(userAddress))) / MAGNITUDE; } if (incRefBonus) reward = SafeMath.add(reward, data.getUserRefBalance(userAddress)); if (incPromoBonus) reward = SafeMath.add(reward, data.getUserTotalPromoBonus(userAddress)); return reward; } //user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus function getUserTotalReward(address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress(); res = SafeMath.add(res, getUserReward(dataContractAddress, userAddress, incShareBonus, incRefBonus, incPromoBonus)); } } //current user's reward function getCurrentUserReward(bool incRefBonus, bool incPromoBonus) public view returns(uint256) { return getUserTotalReward(msg.sender, true, incRefBonus, incPromoBonus); } //current user's total reward from all the tokens on the table function getCurrentUserTotalReward() public view returns(uint256) { return getUserTotalReward(msg.sender, true, true, true); } //user's share bonus from all the tokens on the table function getCurrentUserShareBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, true, false, false); } //current user's ref bonus from all the tokens on the table function getCurrentUserRefBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, false, true, false); } //current user's promo bonus from all the tokens on the table function getCurrentUserPromoBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, false, false, true); } //is ref link available for the user function isRefAvailable(address refAddress) public view returns(bool) { return getUserTotalEthVolumeSaldo(refAddress) >= _minRefEthPurchase; } //is ref link available for the current user function isRefAvailable() public view returns(bool) { return isRefAvailable(msg.sender); } //Withdraws all of the user earnings. function withdrawUserReward() public { uint256 reward = getRewardAndPrepareWithdraw(); require(reward > 0); msg.sender.transfer(reward); emit onWithdrawUserBonus(msg.sender, reward); } //gather all the user's reward and prepare it to withdaw function getRewardAndPrepareWithdraw() internal returns(uint256 reward) { for (uint256 i = 0; i < _controllerContractCount; i++) { address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress(); reward = SafeMath.add(reward, getUserReward(dataContractAddress, msg.sender, true, false, false)); // add share reward to payouts addUserRewardPayouts(dataContractAddress, msg.sender, reward * MAGNITUDE); // add ref bonus reward = SafeMath.add(reward, getUserRefBalance(dataContractAddress, msg.sender)); resetUserRefBalance(dataContractAddress, msg.sender); // add promo bonus reward = SafeMath.add(reward, getUserTotalPromoBonus(dataContractAddress, msg.sender)); resetUserPromoBonus(dataContractAddress, msg.sender); } return reward; } //withdaw all the remamining ETH if there is no one active contract. We don't want to leave them here forever function withdrawRemainingEthAfterAll() onlyAdministrator public { for (uint256 i = 0; i < _controllerContractCount; i++) { if (Etherama(_controllerIndexer[i]).isActive()) revert(); } msg.sender.transfer(address(this).balance); } function calcPercent(uint256 amount, uint256 percent) public pure returns(uint256) { return SafeMath.div(SafeMath.mul(SafeMath.div(amount, 100), percent), 1 ether); } //Converts real num to uint256. Works only with positive numbers. function convertRealTo256(int128 realVal) public pure returns(uint256) { int128 roundedVal = RealMath.fromReal(RealMath.mul(realVal, RealMath.toReal(1e12))); return SafeMath.mul(uint256(roundedVal), uint256(1e6)); } //Converts uint256 to real num. Possible a little loose of precision function convert256ToReal(uint256 val) public pure returns(int128) { uint256 intVal = SafeMath.div(val, 1e6); require(RealMath.isUInt256ValidIn64(intVal)); return RealMath.fraction(int64(intVal), 1e12); } } // Data contract for Etherama contract controller. Data contract cannot be changed so no data can be lost. On the other hand Etherama controller can be replaced if some error is found. contract EtheramaData { // tranding token address address constant public TOKEN_CONTRACT_ADDRESS = 0x83cee9e086A77e492eE0bB93C2B0437aD6fdECCc; // token price in the begining uint256 constant public TOKEN_PRICE_INITIAL = 0.0023 ether; // a percent of the token price which adds/subs each _priceSpeedInterval tokens uint64 constant public PRICE_SPEED_PERCENT = 5; // Token price speed interval. For instance, if PRICE_SPEED_PERCENT = 5 and PRICE_SPEED_INTERVAL = 10000 it means that after 10000 tokens are bought/sold token price will increase/decrease for 5%. uint64 constant public PRICE_SPEED_INTERVAL = 10000; // lock-up period in days. Until this period is expeired nobody can close the contract or withdraw users' funds uint64 constant public EXP_PERIOD_DAYS = 365; mapping(address => bool) private _administrators; uint256 private _administratorCount; uint64 public _initTime; uint64 public _expirationTime; uint256 public _tokenOwnerReward; uint256 public _totalSupply; int128 public _realTokenPrice; address public _controllerAddress = address(0x0); EtheramaCore public _core; uint256 public _initBlockNum; bool public _hasMaxPurchaseLimit = false; IStdToken public _token; //only main contract modifier onlyController() { require(msg.sender == _controllerAddress); _; } constructor(address coreAddress) public { require(coreAddress != address(0x0)); _core = EtheramaCore(coreAddress); _initBlockNum = block.number; } function init() public { require(_controllerAddress == address(0x0)); require(TOKEN_CONTRACT_ADDRESS != address(0x0)); require(RealMath.isUInt64ValidIn64(PRICE_SPEED_PERCENT) && PRICE_SPEED_PERCENT > 0); require(RealMath.isUInt64ValidIn64(PRICE_SPEED_INTERVAL) && PRICE_SPEED_INTERVAL > 0); _controllerAddress = msg.sender; _token = IStdToken(TOKEN_CONTRACT_ADDRESS); _initTime = uint64(now); _expirationTime = _initTime + EXP_PERIOD_DAYS * 1 days; _realTokenPrice = _core.convert256ToReal(TOKEN_PRICE_INITIAL); } function isInited() public view returns(bool) { return (_controllerAddress != address(0x0)); } function getCoreAddress() public view returns(address) { return address(_core); } function setNewControllerAddress(address newAddress) onlyController public { _controllerAddress = newAddress; } function getPromoMinPurchaseEth() public view returns(uint256) { return _core._promoMinPurchaseEth(); } function addAdministator(address addr) onlyController public { _administrators[addr] = true; _administratorCount = SafeMath.add(_administratorCount, 1); } function removeAdministator(address addr) onlyController public { _administrators[addr] = false; _administratorCount = SafeMath.sub(_administratorCount, 1); } function getAdministratorCount() public view returns(uint256) { return _administratorCount; } function isAdministrator(address addr) public view returns(bool) { return _administrators[addr]; } function getCommonInitBlockNum() public view returns (uint256) { return _core.getInitBlockNum(); } function resetTokenOwnerReward() onlyController public { _tokenOwnerReward = 0; } function addTokenOwnerReward(uint256 val) onlyController public { _tokenOwnerReward = SafeMath.add(_tokenOwnerReward, val); } function getCurrentBigPromoBonus() public view returns (uint256) { return _core._currentBigPromoBonus(); } function getCurrentQuickPromoBonus() public view returns (uint256) { return _core._currentQuickPromoBonus(); } function getTotalCollectedPromoBonus() public view returns (uint256) { return _core.getTotalCollectedPromoBonus(); } function setTotalSupply(uint256 val) onlyController public { _totalSupply = val; } function setRealTokenPrice(int128 val) onlyController public { _realTokenPrice = val; } function setHasMaxPurchaseLimit(bool val) onlyController public { _hasMaxPurchaseLimit = val; } function getUserTokenLocalBalance(address userAddress) public view returns(uint256) { return _core.getUserTokenLocalBalance(address(this), userAddress); } function getActualUserTokenBalance(address userAddress) public view returns(uint256) { return SafeMath.min(getUserTokenLocalBalance(userAddress), _token.balanceOf(userAddress)); } function getBonusPerShare() public view returns(uint256) { return _core.getBonusPerShare(address(this)); } function getUserRewardPayouts(address userAddress) public view returns(uint256) { return _core.getUserRewardPayouts(address(this), userAddress); } function getUserRefBalance(address userAddress) public view returns(uint256) { return _core.getUserRefBalance(address(this), userAddress); } function getUserReward(address userAddress, bool incRefBonus, bool incPromoBonus) public view returns(uint256) { return _core.getUserReward(address(this), userAddress, true, incRefBonus, incPromoBonus); } function getUserTotalPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserTotalPromoBonus(address(this), userAddress); } function getUserBigPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserBigPromoBonus(address(this), userAddress); } function getUserQuickPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserQuickPromoBonus(address(this), userAddress); } function getRemainingTokenAmount() public view returns(uint256) { return _token.balanceOf(_controllerAddress); } function getTotalTokenSold() public view returns(uint256) { return _totalSupply - getRemainingTokenAmount(); } function getUserEthVolumeSaldo(address userAddress) public view returns(uint256) { return _core.getUserEthVolumeSaldo(address(this), userAddress); } } contract Etherama { IStdToken public _token; EtheramaData public _data; EtheramaCore public _core; bool public isActive = false; bool public isMigrationToNewControllerInProgress = false; bool public isActualContractVer = true; address public migrationContractAddress = address(0x0); bool public isMigrationApproved = false; address private _creator = address(0x0); event onTokenPurchase(address indexed userAddress, uint256 incomingEth, uint256 tokensMinted, address indexed referredBy); event onTokenSell(address indexed userAddress, uint256 tokensBurned, uint256 ethEarned); event onReinvestment(address indexed userAddress, uint256 ethReinvested, uint256 tokensMinted); event onWithdrawTokenOwnerReward(address indexed toAddress, uint256 ethWithdrawn); event onWinQuickPromo(address indexed userAddress, uint256 ethWon); event onWinBigPromo(address indexed userAddress, uint256 ethWon); // only people with tokens modifier onlyContractUsers() { require(getUserLocalTokenBalance(msg.sender) > 0); _; } // administrators can: // -> change minimal amout of tokens to get a ref link. // administrators CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens // -> suspend the contract modifier onlyAdministrator() { require(isCurrentUserAdministrator()); _; } //core administrator can only approve contract migration after its code review modifier onlyCoreAdministrator() { require(_core.isAdministrator(msg.sender)); _; } // only active state of the contract. Administator can activate it, but canncon deactive untill lock-up period is expired. modifier onlyActive() { require(isActive); _; } // maximum gas price for buy/sell transactions to avoid "front runner" vulnerability. modifier validGasPrice() { require(tx.gasprice <= _core.MAX_GAS_PRICE()); _; } // eth value must be greater than 0 for purchase transactions modifier validPayableValue() { require(msg.value > 0); _; } modifier onlyCoreContract() { require(msg.sender == _data.getCoreAddress()); _; } // dataContractAddress - data contract address where all the data is collected and separated from the controller constructor(address dataContractAddress) public { require(dataContractAddress != address(0x0)); _data = EtheramaData(dataContractAddress); if (!_data.isInited()) { _data.init(); _data.addAdministator(msg.sender); _creator = msg.sender; } _token = _data._token(); _core = _data._core(); } function addAdministator(address addr) onlyAdministrator public { _data.addAdministator(addr); } function removeAdministator(address addr) onlyAdministrator public { _data.removeAdministator(addr); } // transfer ownership request of the contract to token owner from contract creator. The new administator has to accept ownership to finish the transferring. function transferOwnershipRequest(address addr) onlyAdministrator public { addAdministator(addr); } // accept transfer ownership. function acceptOwnership() onlyAdministrator public { require(_creator != address(0x0)); removeAdministator(_creator); require(_data.getAdministratorCount() == 1); } // if there is a maximim purchase limit then a user can buy only amount of tokens which he had before, not more. function setHasMaxPurchaseLimit(bool val) onlyAdministrator public { _data.setHasMaxPurchaseLimit(val); } // activate the controller contract. After calling this function anybody can start trading the contrant's tokens function activate() onlyAdministrator public { require(!isActive); if (getTotalTokenSupply() == 0) setTotalSupply(); require(getTotalTokenSupply() > 0); isActive = true; isMigrationToNewControllerInProgress = false; } // Close the contract and withdraw all the funds. The contract cannot be closed before lock up period is expired. function finish() onlyActive onlyAdministrator public { require(uint64(now) >= _data._expirationTime()); _token.transfer(msg.sender, getRemainingTokenAmount()); msg.sender.transfer(getTotalEthBalance()); isActive = false; } //Converts incoming eth to tokens function buy(address refAddress, uint256 minReturn) onlyActive validGasPrice validPayableValue public payable returns(uint256) { return purchaseTokens(msg.value, refAddress, minReturn); } //sell tokens for eth. before call this func you have to call "approve" in the ERC20 token contract function sell(uint256 tokenAmount, uint256 minReturn) onlyActive onlyContractUsers validGasPrice public returns(uint256) { if (tokenAmount > getCurrentUserLocalTokenBalance() || tokenAmount == 0) return 0; uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true); require(ethAmount >= minReturn); subUserTokens(msg.sender, tokenAmount); msg.sender.transfer(ethAmount); updateTokenPrice(-_core.convert256ToReal(tokenAmount)); distributeFee(totalFeeEth, address(0x0)); uint256 userEthVol = _data.getUserEthVolumeSaldo(msg.sender); _core.trackSell(msg.sender, ethAmount > userEthVol ? userEthVol : ethAmount, tokenAmount); emit onTokenSell(msg.sender, tokenAmount, ethAmount); return ethAmount; } function transferTokens(address toUser, uint256 tokenAmount) onlyActive onlyContractUsers public { require(getUserLocalTokenBalance(msg.sender) >= tokenAmount); _core.subUserTokenLocalBalance(msg.sender, tokenAmount); _core.addUserTokenLocalBalance(toUser, tokenAmount); _token.transferFrom(msg.sender, toUser, tokenAmount); } //Fallback function to handle eth that was sent straight to the contract function() onlyActive validGasPrice validPayableValue payable external { purchaseTokens(msg.value, address(0x0), 1); } // withdraw token owner's reward function withdrawTokenOwnerReward() onlyAdministrator public { uint256 reward = getTokenOwnerReward(); require(reward > 0); _data.resetTokenOwnerReward(); msg.sender.transfer(reward); emit onWithdrawTokenOwnerReward(msg.sender, reward); } // prepare the contract for migration to another one in case of some errors or refining function prepareForMigration() onlyAdministrator public { require(!isMigrationToNewControllerInProgress); isMigrationToNewControllerInProgress = true; } // accept funds transfer to a new controller during a migration. function migrateFunds() payable public { require(isMigrationToNewControllerInProgress); } //HELPERS // max gas price for buy/sell transactions function getMaxGasPrice() public view returns(uint256) { return _core.MAX_GAS_PRICE(); } // max gas price for buy/sell transactions function getExpirationTime() public view returns (uint256) { return _data._expirationTime(); } // time till lock-up period is expired function getRemainingTimeTillExpiration() public view returns (uint256) { if (_data._expirationTime() <= uint64(now)) return 0; return _data._expirationTime() - uint64(now); } function isCurrentUserAdministrator() public view returns(bool) { return _data.isAdministrator(msg.sender); } //data contract address where all the data is holded function getDataContractAddress() public view returns(address) { return address(_data); } // get trading token contract address function getTokenAddress() public view returns(address) { return address(_token); } // request migration to new contract. After request Etherama dev team should review its code and approve it if it is OK function requestControllerContractMigration(address newControllerAddr) onlyAdministrator public { require(!isMigrationApproved); migrationContractAddress = newControllerAddr; } // Dev team gives a pervission to updagrade the contract after code review, transfer all the funds, activate new abilities or fix some errors. function approveControllerContractMigration() onlyCoreAdministrator public { isMigrationApproved = true; } //migrate to new controller contract in case of some mistake in the contract and transfer there all the tokens and eth. It can be done only after code review by Etherama developers. function migrateToNewNewControllerContract() onlyAdministrator public { require(isMigrationApproved && migrationContractAddress != address(0x0) && isActualContractVer); isActive = false; Etherama newController = Etherama(address(migrationContractAddress)); _data.setNewControllerAddress(migrationContractAddress); uint256 remainingTokenAmount = getRemainingTokenAmount(); uint256 ethBalance = getTotalEthBalance(); if (remainingTokenAmount > 0) _token.transfer(migrationContractAddress, remainingTokenAmount); if (ethBalance > 0) newController.migrateFunds.value(ethBalance)(); isActualContractVer = false; } //total buy count function getBuyCount() public view returns(uint256) { return _core.getBuyCount(getDataContractAddress()); } //total sell count function getSellCount() public view returns(uint256) { return _core.getSellCount(getDataContractAddress()); } //total eth volume function getTotalVolumeEth() public view returns(uint256) { return _core.getTotalVolumeEth(getDataContractAddress()); } //total token volume function getTotalVolumeToken() public view returns(uint256) { return _core.getTotalVolumeToken(getDataContractAddress()); } //current bonus per 1 token in ETH function getBonusPerShare() public view returns (uint256) { return SafeMath.div(SafeMath.mul(_data.getBonusPerShare(), 1 ether), _core.MAGNITUDE()); } //token initial price in ETH function getTokenInitialPrice() public view returns(uint256) { return _data.TOKEN_PRICE_INITIAL(); } function getDevRewardPercent() public view returns(uint256) { return _core._devRewardPercent(); } function getTokenOwnerRewardPercent() public view returns(uint256) { return _core._tokenOwnerRewardPercent(); } function getShareRewardPercent() public view returns(uint256) { return _core._shareRewardPercent(); } function getRefBonusPercent() public view returns(uint256) { return _core._refBonusPercent(); } function getBigPromoPercent() public view returns(uint256) { return _core._bigPromoPercent(); } function getQuickPromoPercent() public view returns(uint256) { return _core._quickPromoPercent(); } function getBigPromoBlockInterval() public view returns(uint256) { return _core._bigPromoBlockInterval(); } function getQuickPromoBlockInterval() public view returns(uint256) { return _core._quickPromoBlockInterval(); } function getPromoMinPurchaseEth() public view returns(uint256) { return _core._promoMinPurchaseEth(); } function getPriceSpeedPercent() public view returns(uint64) { return _data.PRICE_SPEED_PERCENT(); } function getPriceSpeedTokenBlock() public view returns(uint64) { return _data.PRICE_SPEED_INTERVAL(); } function getMinRefEthPurchase() public view returns (uint256) { return _core._minRefEthPurchase(); } function getTotalCollectedPromoBonus() public view returns (uint256) { return _data.getTotalCollectedPromoBonus(); } function getCurrentBigPromoBonus() public view returns (uint256) { return _data.getCurrentBigPromoBonus(); } function getCurrentQuickPromoBonus() public view returns (uint256) { return _data.getCurrentQuickPromoBonus(); } //current token price function getCurrentTokenPrice() public view returns(uint256) { return _core.convertRealTo256(_data._realTokenPrice()); } //contract's eth balance function getTotalEthBalance() public view returns(uint256) { return address(this).balance; } //amount of tokens which were funded to the contract initially function getTotalTokenSupply() public view returns(uint256) { return _data._totalSupply(); } //amount of tokens which are still available for selling on the contract function getRemainingTokenAmount() public view returns(uint256) { return _token.balanceOf(address(this)); } //amount of tokens which where sold by the contract function getTotalTokenSold() public view returns(uint256) { return getTotalTokenSupply() - getRemainingTokenAmount(); } //user's token amount which were bought from the contract function getUserLocalTokenBalance(address userAddress) public view returns(uint256) { return _data.getUserTokenLocalBalance(userAddress); } //current user's token amount which were bought from the contract function getCurrentUserLocalTokenBalance() public view returns(uint256) { return getUserLocalTokenBalance(msg.sender); } //is referal link available for the current user function isCurrentUserRefAvailable() public view returns(bool) { return _core.isRefAvailable(); } function getCurrentUserRefBonus() public view returns(uint256) { return _data.getUserRefBalance(msg.sender); } function getCurrentUserPromoBonus() public view returns(uint256) { return _data.getUserTotalPromoBonus(msg.sender); } //max and min values of a deal in tokens function getTokenDealRange() public view returns(uint256, uint256) { return (_core.MIN_TOKEN_DEAL_VAL(), _core.MAX_TOKEN_DEAL_VAL()); } //max and min values of a deal in ETH function getEthDealRange() public view returns(uint256, uint256) { uint256 minTokenVal; uint256 maxTokenVal; (minTokenVal, maxTokenVal) = getTokenDealRange(); return ( SafeMath.max(_core.MIN_ETH_DEAL_VAL(), tokensToEth(minTokenVal, true)), SafeMath.min(_core.MAX_ETH_DEAL_VAL(), tokensToEth(maxTokenVal, true)) ); } //user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus function getUserReward(address userAddress, bool isTotal) public view returns(uint256) { return isTotal ? _core.getUserTotalReward(userAddress, true, true, true) : _data.getUserReward(userAddress, true, true); } //price for selling 1 token. mostly useful only for frontend function get1TokenSellPrice() public view returns(uint256) { uint256 tokenAmount = 1 ether; uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true); return ethAmount; } //price for buying 1 token. mostly useful only for frontend function get1TokenBuyPrice() public view returns(uint256) { uint256 ethAmount = 1 ether; uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); return SafeMath.div(ethAmount * 1 ether, tokenAmount); } //calc current reward for holding @tokenAmount tokens function calcReward(uint256 tokenAmount) public view returns(uint256) { return (uint256) ((int256)(_data.getBonusPerShare() * tokenAmount)) / _core.MAGNITUDE(); } //esimate buy order by amount of ETH/tokens. returns tokens/eth amount after the deal, total fee in ETH and average token price function estimateBuyOrder(uint256 amount, bool fromEth) public view returns(uint256, uint256, uint256) { uint256 minAmount; uint256 maxAmount; (minAmount, maxAmount) = fromEth ? getEthDealRange() : getTokenDealRange(); //require(amount >= minAmount && amount <= maxAmount); uint256 ethAmount = fromEth ? amount : tokensToEth(amount, true); require(ethAmount > 0); uint256 tokenAmount = fromEth ? ethToTokens(amount, true) : amount; uint256 totalFeeEth = calcTotalFee(tokenAmount, true); require(ethAmount > totalFeeEth); uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount); return (fromEth ? tokenAmount : SafeMath.add(ethAmount, totalFeeEth), totalFeeEth, tokenPrice); } //esimate sell order by amount of tokens/ETH. returns eth/tokens amount after the deal, total fee in ETH and average token price function estimateSellOrder(uint256 amount, bool fromToken) public view returns(uint256, uint256, uint256) { uint256 minAmount; uint256 maxAmount; (minAmount, maxAmount) = fromToken ? getTokenDealRange() : getEthDealRange(); //require(amount >= minAmount && amount <= maxAmount); uint256 tokenAmount = fromToken ? amount : ethToTokens(amount, false); require(tokenAmount > 0); uint256 ethAmount = fromToken ? tokensToEth(tokenAmount, false) : amount; uint256 totalFeeEth = calcTotalFee(tokenAmount, false); require(ethAmount > totalFeeEth); uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount); return (fromToken ? ethAmount : tokenAmount, totalFeeEth, tokenPrice); } //returns max user's purchase limit in tokens if _hasMaxPurchaseLimit pamam is set true. If it is a user cannot by more tokens that hs already bought on some other exchange function getUserMaxPurchase(address userAddress) public view returns(uint256) { return _token.balanceOf(userAddress) - SafeMath.mul(getUserLocalTokenBalance(userAddress), 2); } //current urser's max purchase limit in tokens function getCurrentUserMaxPurchase() public view returns(uint256) { return getUserMaxPurchase(msg.sender); } //token owener collected reward function getTokenOwnerReward() public view returns(uint256) { return _data._tokenOwnerReward(); } //current user's won promo bonuses function getCurrentUserTotalPromoBonus() public view returns(uint256) { return _data.getUserTotalPromoBonus(msg.sender); } //current user's won big promo bonuses function getCurrentUserBigPromoBonus() public view returns(uint256) { return _data.getUserBigPromoBonus(msg.sender); } //current user's won quick promo bonuses function getCurrentUserQuickPromoBonus() public view returns(uint256) { return _data.getUserQuickPromoBonus(msg.sender); } //amount of block since core contract is deployed function getBlockNumSinceInit() public view returns(uint256) { return _core.getBlockNumSinceInit(); } //remaing amount of blocks to win a quick promo bonus function getQuickPromoRemainingBlocks() public view returns(uint256) { return _core.getQuickPromoRemainingBlocks(); } //remaing amount of blocks to win a big promo bonus function getBigPromoRemainingBlocks() public view returns(uint256) { return _core.getBigPromoRemainingBlocks(); } // INTERNAL FUNCTIONS function purchaseTokens(uint256 ethAmount, address refAddress, uint256 minReturn) internal returns(uint256) { uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); require(tokenAmount >= minReturn); if (_data._hasMaxPurchaseLimit()) { //user has to have at least equal amount of tokens which he's willing to buy require(getCurrentUserMaxPurchase() >= tokenAmount); } require(tokenAmount > 0 && (SafeMath.add(tokenAmount, getTotalTokenSold()) > getTotalTokenSold())); if (refAddress == msg.sender || !_core.isRefAvailable(refAddress)) refAddress = address(0x0); distributeFee(totalFeeEth, refAddress); addUserTokens(msg.sender, tokenAmount); // the user is not going to receive any reward for the current purchase _core.addUserRewardPayouts(msg.sender, _data.getBonusPerShare() * tokenAmount); checkAndSendPromoBonus(ethAmount); updateTokenPrice(_core.convert256ToReal(tokenAmount)); _core.trackBuy(msg.sender, ethAmount, tokenAmount); emit onTokenPurchase(msg.sender, ethAmount, tokenAmount, refAddress); return tokenAmount; } function setTotalSupply() internal { require(_data._totalSupply() == 0); uint256 tokenAmount = _token.balanceOf(address(this)); _data.setTotalSupply(tokenAmount); } function checkAndSendPromoBonus(uint256 purchaseAmountEth) internal { if (purchaseAmountEth < _data.getPromoMinPurchaseEth()) return; if (getQuickPromoRemainingBlocks() == 0) sendQuickPromoBonus(); if (getBigPromoRemainingBlocks() == 0) sendBigPromoBonus(); } function sendQuickPromoBonus() internal { _core.payoutQuickBonus(msg.sender); emit onWinQuickPromo(msg.sender, _data.getCurrentQuickPromoBonus()); } function sendBigPromoBonus() internal { _core.payoutBigBonus(msg.sender); emit onWinBigPromo(msg.sender, _data.getCurrentBigPromoBonus()); } function distributeFee(uint256 totalFeeEth, address refAddress) internal { addProfitPerShare(totalFeeEth, refAddress); addDevReward(totalFeeEth); addTokenOwnerReward(totalFeeEth); addBigPromoBonus(totalFeeEth); addQuickPromoBonus(totalFeeEth); } function addProfitPerShare(uint256 totalFeeEth, address refAddress) internal { uint256 refBonus = calcRefBonus(totalFeeEth); uint256 totalShareReward = calcTotalShareRewardFee(totalFeeEth); if (refAddress != address(0x0)) { _core.addUserRefBalance.value(refBonus)(refAddress); } else { totalShareReward = SafeMath.add(totalShareReward, refBonus); } if (getTotalTokenSold() == 0) { _data.addTokenOwnerReward(totalShareReward); } else { _core.addBonusPerShare.value(totalShareReward)(); } } function addDevReward(uint256 totalFeeEth) internal { _core.addDevReward.value(calcDevReward(totalFeeEth))(); } function addTokenOwnerReward(uint256 totalFeeEth) internal { _data.addTokenOwnerReward(calcTokenOwnerReward(totalFeeEth)); } function addBigPromoBonus(uint256 totalFeeEth) internal { _core.addBigPromoBonus.value(calcBigPromoBonus(totalFeeEth))(); } function addQuickPromoBonus(uint256 totalFeeEth) internal { _core.addQuickPromoBonus.value(calcQuickPromoBonus(totalFeeEth))(); } function addUserTokens(address user, uint256 tokenAmount) internal { _core.addUserTokenLocalBalance(user, tokenAmount); _token.transfer(msg.sender, tokenAmount); } function subUserTokens(address user, uint256 tokenAmount) internal { _core.subUserTokenLocalBalance(user, tokenAmount); _token.transferFrom(user, address(this), tokenAmount); } function updateTokenPrice(int128 realTokenAmount) public { _data.setRealTokenPrice(calc1RealTokenRateFromRealTokens(realTokenAmount)); } function ethToTokens(uint256 ethAmount, bool isBuy) internal view returns(uint256) { int128 realEthAmount = _core.convert256ToReal(ethAmount); int128 t0 = RealMath.div(realEthAmount, _data._realTokenPrice()); int128 s = getRealPriceSpeed(); int128 tn = RealMath.div(t0, RealMath.toReal(100)); for (uint i = 0; i < 100; i++) { int128 tns = RealMath.mul(tn, s); int128 exptns = RealMath.exp( RealMath.mul(tns, RealMath.toReal(isBuy ? int64(1) : int64(-1))) ); int128 tn1 = RealMath.div( RealMath.mul( RealMath.mul(tns, tn), exptns ) + t0, RealMath.mul( exptns, RealMath.toReal(1) + tns ) ); if (RealMath.abs(tn-tn1) < RealMath.fraction(1, 1e18)) break; tn = tn1; } return _core.convertRealTo256(tn); } function tokensToEth(uint256 tokenAmount, bool isBuy) internal view returns(uint256) { int128 realTokenAmount = _core.convert256ToReal(tokenAmount); int128 s = getRealPriceSpeed(); int128 expArg = RealMath.mul(RealMath.mul(realTokenAmount, s), RealMath.toReal(isBuy ? int64(1) : int64(-1))); int128 realEthAmountFor1Token = RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg)); int128 realEthAmount = RealMath.mul(realTokenAmount, realEthAmountFor1Token); return _core.convertRealTo256(realEthAmount); } function calcTotalFee(uint256 tokenAmount, bool isBuy) internal view returns(uint256) { int128 realTokenAmount = _core.convert256ToReal(tokenAmount); int128 factor = RealMath.toReal(isBuy ? int64(1) : int64(-1)); int128 rateAfterDeal = calc1RealTokenRateFromRealTokens(RealMath.mul(realTokenAmount, factor)); int128 delta = RealMath.div(rateAfterDeal - _data._realTokenPrice(), RealMath.toReal(2)); int128 fee = RealMath.mul(realTokenAmount, delta); //commission for sells is a bit lower due to rounding error if (!isBuy) fee = RealMath.mul(fee, RealMath.fraction(95, 100)); return _core.calcPercent(_core.convertRealTo256(RealMath.mul(fee, factor)), _core._totalIncomeFeePercent()); } function calc1RealTokenRateFromRealTokens(int128 realTokenAmount) internal view returns(int128) { int128 expArg = RealMath.mul(realTokenAmount, getRealPriceSpeed()); return RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg)); } function getRealPriceSpeed() internal view returns(int128) { require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_PERCENT())); require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_INTERVAL())); return RealMath.div(RealMath.fraction(int64(_data.PRICE_SPEED_PERCENT()), 100), RealMath.toReal(int64(_data.PRICE_SPEED_INTERVAL()))); } function calcTotalShareRewardFee(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._shareRewardPercent()); } function calcRefBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._refBonusPercent()); } function calcTokenOwnerReward(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._tokenOwnerRewardPercent()); } function calcDevReward(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._devRewardPercent()); } function calcQuickPromoBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._quickPromoPercent()); } function calcBigPromoBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._bigPromoPercent()); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? b : a; } } //taken from https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol and a bit modified library RealMath { int64 constant MIN_INT64 = int64((uint64(1) << 63)); int64 constant MAX_INT64 = int64(~((uint64(1) << 63))); /** * How many total bits are there? */ int256 constant REAL_BITS = 128; /** * How many fractional bits are there? */ int256 constant REAL_FBITS = 64; /** * How many integer bits are there? */ int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS; /** * What's the first non-fractional bit */ int128 constant REAL_ONE = int128(1) << REAL_FBITS; /** * What's the last fractional bit? */ int128 constant REAL_HALF = REAL_ONE >> 1; /** * What's two? Two is pretty useful. */ int128 constant REAL_TWO = REAL_ONE << 1; /** * And our logarithms are based on ln(2). */ int128 constant REAL_LN_TWO = 762123384786; /** * It is also useful to have Pi around. */ int128 constant REAL_PI = 3454217652358; /** * And half Pi, to save on divides. * TODO: That might not be how the compiler handles constants. */ int128 constant REAL_HALF_PI = 1727108826179; /** * And two pi, which happens to be odd in its most accurate representation. */ int128 constant REAL_TWO_PI = 6908435304715; /** * What's the sign bit? */ int128 constant SIGN_MASK = int128(1) << 127; function getMinInt64() internal pure returns (int64) { return MIN_INT64; } function getMaxInt64() internal pure returns (int64) { return MAX_INT64; } function isUInt256ValidIn64(uint256 val) internal pure returns (bool) { return val >= 0 && val <= uint256(getMaxInt64()); } function isInt256ValidIn64(int256 val) internal pure returns (bool) { return val >= int256(getMinInt64()) && val <= int256(getMaxInt64()); } function isUInt64ValidIn64(uint64 val) internal pure returns (bool) { return val >= 0 && val <= uint64(getMaxInt64()); } function isInt128ValidIn64(int128 val) internal pure returns (bool) { return val >= int128(getMinInt64()) && val <= int128(getMaxInt64()); } /** * Convert an integer to a real. Preserves sign. */ function toReal(int64 ipart) internal pure returns (int128) { return int128(ipart) * REAL_ONE; } /** * Convert a real to an integer. Preserves sign. */ function fromReal(int128 real_value) internal pure returns (int64) { int128 intVal = real_value / REAL_ONE; require(isInt128ValidIn64(intVal)); return int64(intVal); } /** * Get the absolute value of a real. Just the same as abs on a normal int128. */ function abs(int128 real_value) internal pure returns (int128) { if (real_value > 0) { return real_value; } else { return -real_value; } } /** * Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5). */ function fpart(int128 real_value) internal pure returns (int128) { // This gets the fractional part but strips the sign return abs(real_value) % REAL_ONE; } /** * Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5). */ function fpartSigned(int128 real_value) internal pure returns (int128) { // This gets the fractional part but strips the sign int128 fractional = fpart(real_value); return real_value < 0 ? -fractional : fractional; } /** * Get the integer part of a fixed point value. */ function ipart(int128 real_value) internal pure returns (int128) { // Subtract out the fractional part to get the real part. return real_value - fpartSigned(real_value); } /** * Multiply one real by another. Truncates overflows. */ function mul(int128 real_a, int128 real_b) internal pure returns (int128) { // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. return int128((int256(real_a) * int256(real_b)) >> REAL_FBITS); } /** * Divide one real by another real. Truncates overflows. */ function div(int128 real_numerator, int128 real_denominator) internal pure returns (int128) { // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return int128((int256(real_numerator) * REAL_ONE) / int256(real_denominator)); } /** * Create a real from a rational fraction. */ function fraction(int64 numerator, int64 denominator) internal pure returns (int128) { return div(toReal(numerator), toReal(denominator)); } // Now we have some fancy math things (like pow and trig stuff). This isn't // in the RealMath that was deployed with the original Macroverse // deployment, so it needs to be linked into your contract statically. /** * Raise a number to a positive integer power in O(log power) time. * See <https://stackoverflow.com/a/101613> */ function ipow(int128 real_base, int64 exponent) internal pure returns (int128) { if (exponent < 0) { // Negative powers are not allowed here. revert(); } // Start with the 0th power int128 real_result = REAL_ONE; while (exponent != 0) { // While there are still bits set if ((exponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base real_result = mul(real_result, real_base); } // Shift off the low bit exponent = exponent >> 1; // Do the squaring real_base = mul(real_base, real_base); } // Return the final result. return real_result; } /** * Zero all but the highest set bit of a number. * See <https://stackoverflow.com/a/53184> */ function hibit(uint256 val) internal pure returns (uint256) { // Set all the bits below the highest set bit val |= (val >> 1); val |= (val >> 2); val |= (val >> 4); val |= (val >> 8); val |= (val >> 16); val |= (val >> 32); val |= (val >> 64); val |= (val >> 128); return val ^ (val >> 1); } /** * Given a number with one bit set, finds the index of that bit. */ function findbit(uint256 val) internal pure returns (uint8 index) { index = 0; // We and the value with alternating bit patters of various pitches to find it. if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) { // Picth 1 index |= 1; } if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) { // Pitch 2 index |= 2; } if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) { // Pitch 4 index |= 4; } if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) { // Pitch 8 index |= 8; } if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) { // Pitch 16 index |= 16; } if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) { // Pitch 32 index |= 32; } if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) { // Pitch 64 index |= 64; } if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) { // Pitch 128 index |= 128; } } /** * Shift real_arg left or right until it is between 1 and 2. Return the * rescaled value, and the number of bits of right shift applied. Shift may be negative. * * Expresses real_arg as real_scaled * 2^shift, setting shift to put real_arg between [1 and 2). * * Rejects 0 or negative arguments. */ function rescale(int128 real_arg) internal pure returns (int128 real_scaled, int64 shift) { if (real_arg <= 0) { // Not in domain! revert(); } require(isInt256ValidIn64(REAL_FBITS)); // Find the high bit int64 high_bit = findbit(hibit(uint256(real_arg))); // We'll shift so the high bit is the lowest non-fractional bit. shift = high_bit - int64(REAL_FBITS); if (shift < 0) { // Shift left real_scaled = real_arg << -shift; } else if (shift >= 0) { // Shift right real_scaled = real_arg >> shift; } } /** * Calculate the natural log of a number. Rescales the input value and uses * the algorithm outlined at <https://math.stackexchange.com/a/977836> and * the ipow implementation. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function lnLimited(int128 real_arg, int max_iterations) internal pure returns (int128) { if (real_arg <= 0) { // Outside of acceptable domain revert(); } if (real_arg == REAL_ONE) { // Handle this case specially because people will want exactly 0 and // not ~2^-39 ish. return 0; } // We know it's positive, so rescale it to be between [1 and 2) int128 real_rescaled; int64 shift; (real_rescaled, shift) = rescale(real_arg); // Compute the argument to iterate on int128 real_series_arg = div(real_rescaled - REAL_ONE, real_rescaled + REAL_ONE); // We will accumulate the result here int128 real_series_result = 0; for (int64 n = 0; n < max_iterations; n++) { // Compute term n of the series int128 real_term = div(ipow(real_series_arg, 2 * n + 1), toReal(2 * n + 1)); // And add it in real_series_result += real_term; if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Double it to account for the factor of 2 outside the sum real_series_result = mul(real_series_result, REAL_TWO); // Now compute and return the overall result return mul(toReal(shift), REAL_LN_TWO) + real_series_result; } /** * Calculate a natural logarithm with a sensible maximum iteration count to * wait until convergence. Note that it is potentially possible to get an * un-converged value; lack of convergence does not throw. */ function ln(int128 real_arg) internal pure returns (int128) { return lnLimited(real_arg, 100); } /** * Calculate e^x. Uses the series given at * <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function expLimited(int128 real_arg, int max_iterations) internal pure returns (int128) { // We will accumulate the result here int128 real_result = 0; // We use this to save work computing terms int128 real_term = REAL_ONE; for (int64 n = 0; n < max_iterations; n++) { // Add in the term real_result += real_term; // Compute the next term real_term = mul(real_term, div(real_arg, toReal(n + 1))); if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Return the result return real_result; } function expLimited(int128 real_arg, int max_iterations, int k) internal pure returns (int128) { // We will accumulate the result here int128 real_result = 0; // We use this to save work computing terms int128 real_term = REAL_ONE; for (int64 n = 0; n < max_iterations; n++) { // Add in the term real_result += real_term; // Compute the next term real_term = mul(real_term, div(real_arg, toReal(n + 1))); if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } if (n == k) return real_term; // If we somehow never converge I guess we will run out of gas } // Return the result return real_result; } /** * Calculate e^x with a sensible maximum iteration count to wait until * convergence. Note that it is potentially possible to get an un-converged * value; lack of convergence does not throw. */ function exp(int128 real_arg) internal pure returns (int128) { return expLimited(real_arg, 100); } /** * Raise any number to any power, except for negative bases to fractional powers. */ function pow(int128 real_base, int128 real_exponent) internal pure returns (int128) { if (real_exponent == 0) { // Anything to the 0 is 1 return REAL_ONE; } if (real_base == 0) { if (real_exponent < 0) { // Outside of domain! revert(); } // Otherwise it's 0 return 0; } if (fpart(real_exponent) == 0) { // Anything (even a negative base) is super easy to do to an integer power. if (real_exponent > 0) { // Positive integer power is easy return ipow(real_base, fromReal(real_exponent)); } else { // Negative integer power is harder return div(REAL_ONE, ipow(real_base, fromReal(-real_exponent))); } } if (real_base < 0) { // It's a negative base to a non-integer power. // In general pow(-x^y) is undefined, unless y is an int or some // weird rational-number-based relationship holds. revert(); } // If it's not a special case, actually do it. return exp(mul(real_exponent, ln(real_base))); } }
Close the contract and withdraw all the funds. The contract cannot be closed before lock up period is expired.
function finish() onlyActive onlyAdministrator public { require(uint64(now) >= _data._expirationTime()); _token.transfer(msg.sender, getRemainingTokenAmount()); msg.sender.transfer(getTotalEthBalance()); isActive = false; }
1,321,843
./partial_match/1/0xaC8Ed2cda5C82085196e30C5fd4D994fb977F694/sources/ASecureMe.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("ASecure.me", "ASMT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyRevShareFee = 37; uint256 _buyLiquidityFee = 0; uint256 _buyTeamFee = 3; uint256 _sellRevShareFee = 37; uint256 _sellLiquidityFee = 0; uint256 _sellTeamFee = 3; uint256 totalSupply = 1_000_000 * 1e18; buyRevShareFee = _buyRevShareFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee; sellRevShareFee = _sellRevShareFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(revShareWallet, true); excludeFromFees(teamWallet, true); excludeFromMaxTransaction(revShareWallet, true); excludeFromMaxTransaction(teamWallet, true); preListingTransferrable[owner()] = true; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,069,035
./full_match/42/0x8E8d490870615538847e6E57B122FeeEE4eC94F8/sources/browser/token.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "PHOENIX::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
9,568,477
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_226(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,453,939
// File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @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. * * 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. */ 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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/ERC20.sol pragma solidity ^0.5.2; interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns (uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } // File: contracts/kyber/KyberNetworkProxyInterface.sol pragma solidity ^0.5.2; interface KyberNetworkProxyInterface { function maxGasPrice() external view returns (uint); function getUserCapInWei(address user) external view returns (uint); function getUserCapInTokenWei(address user, ERC20 token) external view returns (uint); function enabled() external view returns (bool); function info(bytes32 id) external view returns (uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns (uint); } // File: contracts/community/IDonationCommunity.sol pragma solidity ^0.5.2; interface IDonationCommunity { function donateDelegated(address payable _donator) external payable; function name() external view returns (string memory); function charityVault() external view returns (address); } // File: contracts/kyber/KyberConverter.sol pragma solidity ^0.5.2; contract KyberConverter is Ownable { using SafeMath for uint256; ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); KyberNetworkProxyInterface public kyberNetworkProxyContract; address public walletId; // Events event Swap(address indexed sender, ERC20 srcToken, ERC20 destToken); /** * @dev Payable fallback to receive ETH while converting **/ function() external payable { } constructor (KyberNetworkProxyInterface _kyberNetworkProxyContract, address _walletId) public { kyberNetworkProxyContract = _kyberNetworkProxyContract; walletId = _walletId; } /** * @dev Gets the conversion rate for the destToken given the srcQty. * @param srcToken source token contract address * @param srcQty amount of source tokens * @param destToken destination token contract address */ function getConversionRates( ERC20 srcToken, uint srcQty, ERC20 destToken ) public view returns (uint, uint) { return kyberNetworkProxyContract.getExpectedRate(srcToken, destToken, srcQty); } /** * @dev Swap the user's ERC20 token to ETH * Note: requires 'approve' srcToken first! * @param srcToken source token contract address * @param srcQty amount of source tokens */ function executeSwapMyERCToETH(ERC20 srcToken, uint srcQty) public { swapERCToETH(srcToken, srcQty, msg.sender); emit Swap(msg.sender, srcToken, ETH_TOKEN_ADDRESS); } /** * @dev Swap the user's ERC20 token to ETH and donates to the community. * Note: requires 'approve' srcToken first! * @param srcToken source token contract address * @param srcQty amount of source tokens * @param community address of the donation community */ function executeSwapAndDonate(ERC20 srcToken, uint srcQty, IDonationCommunity community) public { swapERCToETH(srcToken, srcQty, address(this)); // donate ETH to the community community.donateDelegated.value(address(this).balance)(msg.sender); emit Swap(msg.sender, srcToken, ETH_TOKEN_ADDRESS); } function swapERCToETH(ERC20 srcToken, uint srcQty, address destAddress) internal { uint minConversionRate; // Check that the token transferFrom has succeeded require(srcToken.transferFrom(msg.sender, address(this), srcQty)); // Set the spender's token allowance to tokenQty require(srcToken.approve(address(kyberNetworkProxyContract), srcQty)); // Get the minimum conversion rate (minConversionRate,) = kyberNetworkProxyContract.getExpectedRate(srcToken, ETH_TOKEN_ADDRESS, srcQty); // -5% max minConversionRate = minConversionRate.mul(95).div(100); // +5% max uint maxDestAmount = srcQty.mul(minConversionRate).mul(105).div(100); // Swap the ERC20 token and send to 'this' contract address bytes memory hint; uint256 amount = kyberNetworkProxyContract.tradeWithHint( srcToken, srcQty, ETH_TOKEN_ADDRESS, destAddress, maxDestAmount, minConversionRate, walletId, hint ); // Return the change of src token uint256 change = srcToken.balanceOf(address(this)); if (change > 0) { require( srcToken.transfer(msg.sender, change), "Could not transfer change to sender" ); } } function executeSwapMyETHToERC(address _ercAddress) public payable returns (uint256) { uint minConversionRate; uint srcQty = msg.value; address destAddress = msg.sender; ERC20 ercToken = ERC20(_ercAddress); // Get the minimum conversion rate (minConversionRate,) = kyberNetworkProxyContract.getExpectedRate(ETH_TOKEN_ADDRESS, ercToken, srcQty); uint maxDestAmount = srcQty.mul(minConversionRate).mul(105).div(100); // 5% // Swap the ERC20 token and send to destAddress bytes memory hint; uint256 amount = kyberNetworkProxyContract.tradeWithHint.value(srcQty)( ETH_TOKEN_ADDRESS, srcQty, ercToken, destAddress, maxDestAmount, minConversionRate, walletId, hint ); // Return the change of ETH if any uint256 change = address(this).balance; if (change > 0) { address(msg.sender).transfer(change); } // Log the event emit Swap(msg.sender, ETH_TOKEN_ADDRESS, ercToken); return amount; } /** * @dev Recovery for the remaining change */ function withdraw() public onlyOwner { require(address(this).balance > 0, "Insufficient funds to withdraw"); msg.sender.transfer(address(this).balance); } }
Check that the token transferFrom has succeeded Set the spender's token allowance to tokenQty Get the minimum conversion rate -5% max +5% max Swap the ERC20 token and send to 'this' contract address Return the change of src token
function swapERCToETH(ERC20 srcToken, uint srcQty, address destAddress) internal { uint minConversionRate; require(srcToken.transferFrom(msg.sender, address(this), srcQty)); require(srcToken.approve(address(kyberNetworkProxyContract), srcQty)); (minConversionRate,) = kyberNetworkProxyContract.getExpectedRate(srcToken, ETH_TOKEN_ADDRESS, srcQty); minConversionRate = minConversionRate.mul(95).div(100); uint maxDestAmount = srcQty.mul(minConversionRate).mul(105).div(100); bytes memory hint; uint256 amount = kyberNetworkProxyContract.tradeWithHint( srcToken, srcQty, ETH_TOKEN_ADDRESS, destAddress, maxDestAmount, minConversionRate, walletId, hint ); uint256 change = srcToken.balanceOf(address(this)); if (change > 0) { require( srcToken.transfer(msg.sender, change), "Could not transfer change to sender" ); } }
7,761,708
./full_match/42/0xc771073bdE9D13CB6F427e2a136504C2532f3C4B/sources/ERC20.sol
Transfer tokens from one address to another from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of tokens to be transferred/
function transferFrom(address from,address to,uint256 value)override public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; }
16,266,105
./full_match/1/0xC383AAc4B3dC18D9ce08AB7F63B4632716F1e626/sources/src/contracts/ScaledBalanceTokenBase.sol
@inheritdoc IScaledBalanceToken
function getScaledUserBalanceAndSupply( address user ) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); }
3,095,131
pragma solidity ^0.4.24; contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract StandardToken is ERC20, SafeMath { mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract ViotToken is Ownable, StandardToken { string public name = "VIOT Token"; string public symbol = "VIOT"; uint public decimals = 18; // token has 18 digit precision uint public totalSupply = 1 * (10**9) * (10**18); // 1 Billion Tokens /// @notice Initializes the contract and allocates all initial tokens to the owner and agreement account function ViotToken() { balances[msg.sender] = totalSupply; } // Don't accept ethers - no payable modifier function () { } /// @notice To transfer token contract ownership /// @param _newOwner The address of the new owner of this contract function transferOwnership(address _newOwner) onlyOwner { balances[_newOwner] = safeAdd(balances[owner], balances[_newOwner]); balances[owner] = 0; Ownable.transferOwnership(_newOwner); } // Owner can transfer out any ERC20 tokens sent in by mistake function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, amount); } }
Don't accept ethers - no payable modifier
function () { }
262,030
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; pragma experimental ABIEncoderV2; import "./Utils.sol"; import "./InnerProductVerifier.sol"; contract BurnVerifier { using Utils for uint256; using Utils for Utils.G1Point; InnerProductVerifier ip; struct BurnStatement { Utils.G1Point CLn; Utils.G1Point CRn; Utils.G1Point y; uint256 epoch; // or uint8? address sender; Utils.G1Point u; } struct BurnProof { Utils.G1Point BA; Utils.G1Point BS; Utils.G1Point T_1; Utils.G1Point T_2; uint256 tHat; uint256 mu; uint256 c; uint256 s_sk; uint256 s_b; uint256 s_tau; InnerProductVerifier.InnerProductProof ipProof; } constructor(address _ip) { ip = InnerProductVerifier(_ip); } function verifyBurn(Utils.G1Point memory CLn, Utils.G1Point memory CRn, Utils.G1Point memory y, uint256 epoch, Utils.G1Point memory u, address sender, bytes memory proof) public view returns (bool) { BurnStatement memory statement; // WARNING: if this is called directly in the console, // and your strings are less than 64 characters, they will be padded on the right, not the left. should hopefully not be an issue, // as this will typically be called simply by the other contract. still though, beware statement.CLn = CLn; statement.CRn = CRn; statement.y = y; statement.epoch = epoch; statement.u = u; statement.sender = sender; BurnProof memory burnProof = unserialize(proof); return verify(statement, burnProof); } struct BurnAuxiliaries { uint256 y; uint256[32] ys; uint256 z; uint256[1] zs; // silly. just to match zether. uint256 zSum; uint256[32] twoTimesZSquared; uint256 x; uint256 t; uint256 k; Utils.G1Point tEval; } struct SigmaAuxiliaries { uint256 c; Utils.G1Point A_y; Utils.G1Point A_b; Utils.G1Point A_t; Utils.G1Point gEpoch; Utils.G1Point A_u; } struct IPAuxiliaries { Utils.G1Point P; Utils.G1Point u_x; Utils.G1Point[] hPrimes; Utils.G1Point hPrimeSum; uint256 o; } function gSum() internal pure returns (Utils.G1Point memory) { return Utils.G1Point(0x2257118d30fe5064dda298b2fac15cf96fd51f0e7e3df342d0aed40b8d7bb151, 0x0d4250e7509c99370e6b15ebfe4f1aa5e65a691133357901aa4b0641f96c80a8); } function verify(BurnStatement memory statement, BurnProof memory proof) internal view returns (bool) { uint256 statementHash = uint256(keccak256(abi.encode(statement.CLn, statement.CRn, statement.y, statement.epoch, statement.sender))).mod(); // stacktoodeep? BurnAuxiliaries memory burnAuxiliaries; burnAuxiliaries.y = uint256(keccak256(abi.encode(statementHash, proof.BA, proof.BS))).mod(); burnAuxiliaries.ys[0] = 1; burnAuxiliaries.k = 1; for (uint256 i = 1; i < 32; i++) { burnAuxiliaries.ys[i] = burnAuxiliaries.ys[i - 1].mul(burnAuxiliaries.y); burnAuxiliaries.k = burnAuxiliaries.k.add(burnAuxiliaries.ys[i]); } burnAuxiliaries.z = uint256(keccak256(abi.encode(burnAuxiliaries.y))).mod(); burnAuxiliaries.zs[0] = burnAuxiliaries.z.mul(burnAuxiliaries.z); burnAuxiliaries.zSum = burnAuxiliaries.zs[0].mul(burnAuxiliaries.z); // trivial sum burnAuxiliaries.k = burnAuxiliaries.k.mul(burnAuxiliaries.z.sub(burnAuxiliaries.zs[0])).sub(burnAuxiliaries.zSum.mul(1 << 32).sub(burnAuxiliaries.zSum)); burnAuxiliaries.t = proof.tHat.sub(burnAuxiliaries.k); for (uint256 i = 0; i < 32; i++) { burnAuxiliaries.twoTimesZSquared[i] = burnAuxiliaries.zs[0].mul(1 << i); } burnAuxiliaries.x = uint256(keccak256(abi.encode(burnAuxiliaries.z, proof.T_1, proof.T_2))).mod(); burnAuxiliaries.tEval = proof.T_1.mul(burnAuxiliaries.x).add(proof.T_2.mul(burnAuxiliaries.x.mul(burnAuxiliaries.x))); // replace with "commit"? SigmaAuxiliaries memory sigmaAuxiliaries; sigmaAuxiliaries.A_y = Utils.g().mul(proof.s_sk).add(statement.y.mul(proof.c.neg())); sigmaAuxiliaries.A_b = Utils.g().mul(proof.s_b).add(statement.CRn.mul(proof.s_sk).add(statement.CLn.mul(proof.c.neg())).mul(burnAuxiliaries.zs[0])); sigmaAuxiliaries.A_t = Utils.g().mul(burnAuxiliaries.t).add(burnAuxiliaries.tEval.neg()).mul(proof.c).add(Utils.h().mul(proof.s_tau)).add(Utils.g().mul(proof.s_b.neg())); sigmaAuxiliaries.gEpoch = Utils.mapInto("Zether", statement.epoch); sigmaAuxiliaries.A_u = sigmaAuxiliaries.gEpoch.mul(proof.s_sk).add(statement.u.mul(proof.c.neg())); sigmaAuxiliaries.c = uint256(keccak256(abi.encode(burnAuxiliaries.x, sigmaAuxiliaries.A_y, sigmaAuxiliaries.A_b, sigmaAuxiliaries.A_t, sigmaAuxiliaries.A_u))).mod(); require(sigmaAuxiliaries.c == proof.c, "Sigma protocol challenge equality failure."); IPAuxiliaries memory ipAuxiliaries; ipAuxiliaries.o = uint256(keccak256(abi.encode(sigmaAuxiliaries.c))).mod(); ipAuxiliaries.u_x = Utils.h().mul(ipAuxiliaries.o); ipAuxiliaries.hPrimes = new Utils.G1Point[](32); for (uint256 i = 0; i < 32; i++) { ipAuxiliaries.hPrimes[i] = ip.hs(i).mul(burnAuxiliaries.ys[i].inv()); ipAuxiliaries.hPrimeSum = ipAuxiliaries.hPrimeSum.add(ipAuxiliaries.hPrimes[i].mul(burnAuxiliaries.ys[i].mul(burnAuxiliaries.z).add(burnAuxiliaries.twoTimesZSquared[i]))); } ipAuxiliaries.P = proof.BA.add(proof.BS.mul(burnAuxiliaries.x)).add(gSum().mul(burnAuxiliaries.z.neg())).add(ipAuxiliaries.hPrimeSum); ipAuxiliaries.P = ipAuxiliaries.P.add(Utils.h().mul(proof.mu.neg())); ipAuxiliaries.P = ipAuxiliaries.P.add(ipAuxiliaries.u_x.mul(proof.tHat)); require(ip.verifyInnerProduct(ipAuxiliaries.hPrimes, ipAuxiliaries.u_x, ipAuxiliaries.P, proof.ipProof, ipAuxiliaries.o), "Inner product proof verification failed."); return true; } function unserialize(bytes memory arr) internal pure returns (BurnProof memory proof) { proof.BA = Utils.G1Point(Utils.slice(arr, 0), Utils.slice(arr, 32)); proof.BS = Utils.G1Point(Utils.slice(arr, 64), Utils.slice(arr, 96)); proof.T_1 = Utils.G1Point(Utils.slice(arr, 128), Utils.slice(arr, 160)); proof.T_2 = Utils.G1Point(Utils.slice(arr, 192), Utils.slice(arr, 224)); proof.tHat = uint256(Utils.slice(arr, 256)); proof.mu = uint256(Utils.slice(arr, 288)); proof.c = uint256(Utils.slice(arr, 320)); proof.s_sk = uint256(Utils.slice(arr, 352)); proof.s_b = uint256(Utils.slice(arr, 384)); proof.s_tau = uint256(Utils.slice(arr, 416)); InnerProductVerifier.InnerProductProof memory ipProof; ipProof.L = new Utils.G1Point[](5); ipProof.R = new Utils.G1Point[](5); for (uint256 i = 0; i < 5; i++) { // 2^5 = 32. ipProof.L[i] = Utils.G1Point(Utils.slice(arr, 448 + i * 64), Utils.slice(arr, 480 + i * 64)); ipProof.R[i] = Utils.G1Point(Utils.slice(arr, 448 + (5 + i) * 64), Utils.slice(arr, 480 + (5 + i) * 64)); } ipProof.a = uint256(Utils.slice(arr, 448 + 5 * 128)); ipProof.b = uint256(Utils.slice(arr, 480 + 5 * 128)); proof.ipProof = ipProof; return proof; } }
and your strings are less than 64 characters, they will be padded on the right, not the left. should hopefully not be an issue, as this will typically be called simply by the other contract. still though, beware
function verifyBurn(Utils.G1Point memory CLn, Utils.G1Point memory CRn, Utils.G1Point memory y, uint256 epoch, Utils.G1Point memory u, address sender, bytes memory proof) public view returns (bool) { statement.CLn = CLn; statement.CRn = CRn; statement.y = y; statement.epoch = epoch; statement.u = u; statement.sender = sender; BurnProof memory burnProof = unserialize(proof); return verify(statement, burnProof); }
13,116,473
pragma solidity ^0.5.16; import "../CToken.sol"; import "../ErrorReporter.sol"; import "../PriceOracle.sol"; import "../ComptrollerInterface.sol"; import "../Unitroller.sol"; import "./CWComptrollerStorage.sol"; /** * @title CloudWalk's Comptroller Contract * @author Compound (CloudWalk) */ contract CWComptroller is CWComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when market.onlyTrustedSuppliers config is changed event OnlyTrustedSuppliers(CToken indexed cToken, bool state); /// @notice Emitted when market.onlyTrustedBorrowers config is changed event OnlyTrustedBorrowers(CToken indexed cToken, bool state); // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 1.0e18; // 1.0 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } (bool exists, ) = CToken(cToken).getTrustedSupplier(minter); if (exists) { (Error err, , uint shortfall) = getTrustedSupplierLiquidityInternal(minter, CToken(cToken), mintAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.TRUSTED_SUPPLY_ALLOWANCE_OVERFLOW); } } else if (markets[cToken].onlyTrustedSuppliers) { return uint(Error.UNTRUSTED_SUPPLIER_ACCOUNT); } return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (bool exists, ) = CToken(cToken).getTrustedBorrower(borrower); if (exists) { (Error err, , uint shortfall) = getTrustedBorrowerLiquidityInternal(borrower, CToken(cToken), borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.TRUSTED_BORROW_ALLOWANCE_OVERFLOW); } } else if (markets[cToken].onlyTrustedBorrowers) { return uint(Error.UNTRUSTED_BORROWER_ACCOUNT); } else { (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } } return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, onlyTrustedSuppliers: true, onlyTrustedBorrowers: true, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /*** Trusted Accounts ***/ /** * @notice Determine what the trusted account liquidity would be if the given amount borrowed * @param cToken The market to borrow from * @param account The account to determine liquidity for * @param borrowAmount The amount of underlying token to borrow * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedBorrowerLiquidity(address account, address cToken, uint borrowAmount) external view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getTrustedBorrowerLiquidityInternal(account, CToken(cToken), borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the trusted account liquidity would be if the given amount borrowed * @param cToken The market to borrow from * @param account The account to determine liquidity for * @param borrowAmount The amount of underlying token to borrow * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedBorrowerLiquidityInternal(address account, CToken cToken, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; uint borrowBalance; // Read trusted borrower data (bool exists, uint borrowAllowance) = cToken.getTrustedBorrower(account); if (!exists) { return (Error.UNTRUSTED_BORROWER_ACCOUNT, 0, 0); } // Read borrow balance (oErr, , borrowBalance, ) = cToken.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } borrowBalance = add_(borrowBalance, borrowAmount); // These are safe, as the underflow condition is checked first if (borrowAllowance > borrowBalance) { return (Error.NO_ERROR, borrowAllowance - borrowBalance, 0); } else { return (Error.NO_ERROR, 0, borrowBalance - borrowAllowance); } } /** * @notice Determine what the trusted account liquidity would be if the given amount supplied * @param cToken The market to supply in * @param account The account to determine liquidity for * @param supplyAmount The amount of underlying token to supply * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedSupplierLiquidity(address account, address cToken, uint supplyAmount) external view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getTrustedSupplierLiquidityInternal(account, CToken(cToken), supplyAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amount borrowed * @param cToken The market to borrow from * @param account The account to determine liquidity for * @param supplyAmount The amount of underlying to supply * @dev Note that liquidity and shortfall are returned as an amount of undelying token * @return (possible error code, account liquidity in excess of allowance, * account shortfall below allowance) */ function getTrustedSupplierLiquidityInternal(address account, CToken cToken, uint supplyAmount) internal view returns (Error, uint, uint) { uint oErr; uint supplyBalance; uint exchangeRateMantissa; // Read trusted supplier data (bool exists, uint supplyAllowance) = cToken.getTrustedSupplier(account); if (!exists) { return (Error.UNTRUSTED_SUPPLIER_ACCOUNT, 0, 0); } // Read cToken balance (oErr, supplyBalance, , exchangeRateMantissa) = cToken.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } supplyBalance = mul_ScalarTruncateAddUInt(Exp({mantissa: exchangeRateMantissa}), supplyBalance, supplyAmount); // These are safe, as the underflow condition is checked first if (supplyAllowance > supplyBalance) { return (Error.NO_ERROR, supplyAllowance - supplyBalance, 0); } else { return (Error.NO_ERROR, 0, supplyBalance - supplyAllowance); } } function _setOnlyTrustedSuppliers(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "market is not listed"); require(msg.sender == admin, "caller is not admin"); markets[address(cToken)].onlyTrustedSuppliers = state; emit OnlyTrustedSuppliers(cToken, state); return state; } function _setOnlyTrustedBorrowers(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "market is not listed"); require(msg.sender == admin, "caller is not admin"); markets[address(cToken)].onlyTrustedBorrowers = state; emit OnlyTrustedBorrowers(cToken, state); return state; } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } /*** Trsuted Accounts ***/ function getTrustedSupplier(address account) external view returns (bool, uint) { TrustedAccount memory supplier = trustedSuppliers[account]; return (supplier.exists, supplier.allowance); } function getTrustedBorrower(address account) external view returns (bool, uint) { TrustedAccount memory borrower = trustedBorrowers[account]; return (borrower.exists, borrower.allowance); } function getTrustedAdmin(address account) external view returns (bool) { return trustedAdmins[account]; } function _setTrustedSupplier(address account, bool exists, uint supplyAllowance) external returns (uint) { if (msg.sender != admin && !trustedAdmins[msg.sender]) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_TRUSTED_SUPPLIER_ADMIN_CHECK); } TrustedAccount storage supplier = trustedSuppliers[account]; emit TrustedSupplier(account, supplier.exists, supplier.allowance, exists, supplyAllowance); supplier.allowance = supplyAllowance; supplier.exists = exists; return uint(Error.NO_ERROR); } function _setTrustedBorrower(address account, bool exists, uint borrowAllowance) external returns (uint) { if (msg.sender != admin && !trustedAdmins[msg.sender]) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_TRUSTED_BORROWER_ADMIN_CHECK); } TrustedAccount storage borrower = trustedBorrowers[account]; emit TrustedBorrower(account, borrower.exists, borrower.allowance, exists, borrowAllowance); borrower.allowance = borrowAllowance; borrower.exists = exists; return uint(Error.NO_ERROR); } function _setTrustedAdmin(address account, bool enabled) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_TRUSTED_ADMIN_ACCOUNT_ADMIN_CHECK); } trustedAdmins[account] = enabled; emit TrustedAdmin(account, enabled); return uint(Error.NO_ERROR); } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY, UNTRUSTED_SUPPLIER_ACCOUNT, UNTRUSTED_BORROWER_ACCOUNT, TRUSTED_SUPPLY_ALLOWANCE_OVERFLOW, TRUSTED_BORROW_ALLOWANCE_OVERFLOW } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE, SET_TRUSTED_SUPPLIER_ADMIN_CHECK, SET_TRUSTED_BORROWER_ADMIN_CHECK, TRUSTED_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SET_TRUSTED_ADMIN_ACCOUNT_ADMIN_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma solidity ^0.5.16; import "../CToken.sol"; import "../ComptrollerStorage.sol"; contract CWComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /// @notice Determines if only trusted suppliers allowed bool onlyTrustedSuppliers; /// @notice Determines if only trusted borrowers allowed bool onlyTrustedBorrowers; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract CWComptrollerV3Storage is CWComptrollerV2Storage { /// @notice A list of all markets CToken[] public allMarkets; } contract CWComptrollerV4Storage is CWComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./EIP20NonStandardInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.005% / block) */ uint internal constant borrowRateMaxMantissa = 0.005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; /** * @notice Container for trusted account information */ struct TrustedAccount { uint allowance; bool exists; } /** * @notice Trusted suppliers mapping */ mapping(address => TrustedAccount) internal trustedSuppliers; /** * @notice Trusted borrowers mapping */ mapping(address => TrustedAccount) internal trustedBorrowers; /** * @notice Trusted admins mapping */ mapping(address => bool) internal trustedAdmins; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /** * @notice Event emitted when trusted supplier is configured */ event TrustedSupplier(address indexed account, bool oldExists, uint oldAllowance, bool newExists, uint newAllowance); /** * @notice Event emitted when trusted borrower is configured */ event TrustedBorrower(address indexed account, bool oldExists, uint oldAllowance, bool newExists, uint newAllowance); /** * @notice Event emitted when trusted admin is configured */ event TrustedAdmin(address indexed account, bool enabled); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); /*** Trusted Functions ***/ function getTrustedAdmin(address account) external view returns (bool); function getTrustedSupplier(address account) external view returns (bool, uint); function getTrustedBorrower(address account) external view returns (bool, uint); function _setTrustedAdmin(address account, bool enabled) external returns (uint); function _setTrustedSupplier(address account, bool exists, uint supplyAllowance) external returns (uint); function _setTrustedBorrower(address account, bool exists, uint borrowAllowance) external returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); function sweepToken(EIP20NonStandardInterface token) external; /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage { /// @notice The portion of COMP that each contributor receives per block mapping(address => uint) public compContributorSpeeds; /// @notice Last block at which a contributor's COMP rewards have been allocated mapping(address => uint) public lastContributorBlock; }
account shortfall below allowance)/
function getTrustedSupplierLiquidity(address account, address cToken, uint supplyAmount) external view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getTrustedSupplierLiquidityInternal(account, CToken(cToken), supplyAmount); return (uint(err), liquidity, shortfall); account liquidity in excess of allowance, }
14,523,923
/** *Submitted for verification at BscScan.com on 2021-07-02 */ // File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @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() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/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]. */ 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 // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @pancakeswap\pancake-swap-lib\contracts\math\SafeMath.sol pragma solidity >=0.4.0; /** * @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) { 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; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @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 ); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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" ); // 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" ); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol pragma solidity ^0.8.0; /** * @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' // solhint-disable-next-line max-line-length 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 // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/interfaces/IRandomNumberGenerator.sol pragma solidity ^0.8.4; interface IRandomNumberGenerator { /** * Requests randomness from a user-provided seed */ function getRandomNumber(uint256 _seed) external; /** * View latest lotteryId numbers */ function viewLatestLotteryId() external view returns (uint256); /** * Views random result */ function viewRandomResult() external view returns (uint32); } // File: contracts/interfaces/IBirbLottery.sol pragma solidity ^0.8.4; interface IBirbLottery { /** * @notice Buy tickets for the current lottery * @param _lotteryId: lotteryId * @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999 * @dev Callable by users */ function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers) external; /** * @notice Claim a set of winning tickets for a lottery * @param _lotteryId: lottery id * @param _ticketIds: array of ticket ids * @param _brackets: array of brackets for the ticket ids * @dev Callable by users only, not contract! */ function claimTickets( uint256 _lotteryId, uint256[] calldata _ticketIds, uint32[] calldata _brackets ) external; /** * @notice Close lottery * @param _lotteryId: lottery id * @dev Callable by operator */ function closeLottery(uint256 _lotteryId) external; /** * @notice Draw the final number, calculate reward in BIRB per group, and make lottery claimable * @param _lotteryId: lottery id * @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all) * @dev Callable by operator */ function drawFinalNumberAndMakeLotteryClaimable( uint256 _lotteryId, bool _autoInjection ) external; /** * @notice Inject funds * @param _lotteryId: lottery id * @param _amount: amount to inject in BIRB token * @dev Callable by operator */ function injectFunds(uint256 _lotteryId, uint256 _amount) external; /** * @notice Start the lottery * @dev Callable by operator * @param _endTime: endTime of the lottery * @param _priceTicketInBirb: price of a ticket in BIRB * @param _discountDivisor: the divisor to calculate the discount magnitude for bulks * @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000) * @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%) */ function startLottery( uint256 _endTime, uint256 _priceTicketInBirb, uint256 _discountDivisor, uint256[6] calldata _rewardsBreakdown, uint256 _treasuryFee ) external; /** * @notice View current lottery id */ function viewCurrentLotteryId() external returns (uint256); } // File: contracts/BirbLottery.sol pragma solidity ^0.8.4; pragma abicoder v2; /** @title BirbSwap Lottery. * @notice It is a contract for a lottery system using * randomness provided externally. */ contract BirbLottery is ReentrancyGuard, IBirbLottery, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; address public injectorAddress; address public operatorAddress; address public treasuryAddress; uint256 public currentLotteryId; uint256 public currentTicketId; uint256 public maxNumberTicketsPerBuyOrClaim = 100; uint256 public maxPriceTicketInBirb = 50 ether; uint256 public minPriceTicketInBirb = 0.005 ether; uint256 public pendingInjectionNextLottery; uint256 public constant MIN_DISCOUNT_DIVISOR = 300; uint256 public constant MIN_LENGTH_LOTTERY = 4 hours - 5 minutes; // 4 hours uint256 public constant MAX_LENGTH_LOTTERY = 4 days + 5 minutes; // 4 days uint256 public constant MAX_TREASURY_FEE = 3000; // 30% IERC20 public birbToken; IRandomNumberGenerator public randomGenerator; enum Status { Pending, Open, Close, Claimable } struct Lottery { Status status; uint256 startTime; uint256 endTime; uint256 priceTicketInBirb; uint256 discountDivisor; uint256[6] rewardsBreakdown; // 0: 1 matching number // 5: 6 matching numbers uint256 treasuryFee; // 500: 5% // 200: 2% // 50: 0.5% uint256[6] birbPerBracket; uint256[6] countWinnersPerBracket; uint256 firstTicketId; uint256 firstTicketIdNextLottery; uint256 amountCollectedInBirb; uint32 finalNumber; } struct Ticket { uint32 number; address owner; } // Mapping are cheaper than arrays mapping(uint256 => Lottery) private _lotteries; mapping(uint256 => Ticket) private _tickets; // Bracket calculator is used for verifying claims for ticket prizes mapping(uint32 => uint32) private _bracketCalculator; // Keeps track of number of ticket per unique combination for each lotteryId mapping(uint256 => mapping(uint32 => uint256)) private _numberTicketsPerLotteryId; // Keep track of user ticket ids for a given lotteryId mapping(address => mapping(uint256 => uint256[])) private _userTicketIdsPerLotteryId; modifier notContract() { require(!_isContract(msg.sender), "Contract not allowed"); require(msg.sender == tx.origin, "Proxy contract not allowed"); _; } modifier onlyOperator() { require(msg.sender == operatorAddress, "Not operator"); _; } modifier onlyOwnerOrInjector() { require( (msg.sender == owner()) || (msg.sender == injectorAddress), "Not owner or injector" ); _; } event AdminTokenRecovery(address token, uint256 amount); event LotteryClose( uint256 indexed lotteryId, uint256 firstTicketIdNextLottery ); event LotteryInjection(uint256 indexed lotteryId, uint256 injectedAmount); event LotteryOpen( uint256 indexed lotteryId, uint256 startTime, uint256 endTime, uint256 priceTicketInBirb, uint256 firstTicketId, uint256 injectedAmount ); event LotteryNumberDrawn( uint256 indexed lotteryId, uint256 finalNumber, uint256 countWinningTickets ); event NewOperatorAndTreasuryAndInjectorAddresses( address operator, address treasury, address injector ); event NewRandomGenerator(address indexed randomGenerator); event TicketsPurchase( address indexed buyer, uint256 indexed lotteryId, uint256 numberTickets ); event TicketsClaim( address indexed claimer, uint256 amount, uint256 indexed lotteryId, uint256 numberTickets ); /** * @notice Constructor * @dev RandomNumberGenerator must be deployed prior to this contract * @param _birbTokenAddress: address of the BIRB token * @param _randomGeneratorAddress: address of the RandomGenerator contract used to work with ChainLink VRF */ constructor(address _birbTokenAddress, address _randomGeneratorAddress) { birbToken = IERC20(_birbTokenAddress); randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress); // Initializes a mapping _bracketCalculator[0] = 1; _bracketCalculator[1] = 11; _bracketCalculator[2] = 111; _bracketCalculator[3] = 1111; _bracketCalculator[4] = 11111; _bracketCalculator[5] = 111111; } /** * @notice Buy tickets for the current lottery * @param _lotteryId: lotteryId * @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999 * @dev Callable by users */ function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers) external override notContract nonReentrant { require(_ticketNumbers.length != 0, "No ticket specified"); require( _ticketNumbers.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets" ); require( _lotteries[_lotteryId].status == Status.Open, "Lottery is not open" ); require( block.timestamp < _lotteries[_lotteryId].endTime, "Lottery is over" ); // Calculate number of BIRB to this contract uint256 amountBirbToTransfer = _calculateTotalPriceForBulkTickets( _lotteries[_lotteryId].discountDivisor, _lotteries[_lotteryId].priceTicketInBirb, _ticketNumbers.length ); // Transfer birb tokens to this contract uint256 balanceBefore = birbToken.balanceOf(address(this)); birbToken.safeTransferFrom( address(msg.sender), address(this), amountBirbToTransfer ); amountBirbToTransfer = birbToken.balanceOf(address(this)).sub( balanceBefore ); // Increment the total amount collected for the lottery round _lotteries[_lotteryId].amountCollectedInBirb = _lotteries[_lotteryId] .amountCollectedInBirb .add(amountBirbToTransfer); for (uint256 i = 0; i < _ticketNumbers.length; i++) { uint32 thisTicketNumber = _ticketNumbers[i]; require( (thisTicketNumber >= 1000000) && (thisTicketNumber <= 1999999), "Outside range" ); _numberTicketsPerLotteryId[_lotteryId][ 1 + (thisTicketNumber % 10) ]++; _numberTicketsPerLotteryId[_lotteryId][ 11 + (thisTicketNumber % 100) ]++; _numberTicketsPerLotteryId[_lotteryId][ 111 + (thisTicketNumber % 1000) ]++; _numberTicketsPerLotteryId[_lotteryId][ 1111 + (thisTicketNumber % 10000) ]++; _numberTicketsPerLotteryId[_lotteryId][ 11111 + (thisTicketNumber % 100000) ]++; _numberTicketsPerLotteryId[_lotteryId][ 111111 + (thisTicketNumber % 1000000) ]++; _userTicketIdsPerLotteryId[msg.sender][_lotteryId].push( currentTicketId ); _tickets[currentTicketId] = Ticket({ number: thisTicketNumber, owner: msg.sender }); // Increase lottery ticket number currentTicketId++; } emit TicketsPurchase(msg.sender, _lotteryId, _ticketNumbers.length); } /** * @notice Claim a set of winning tickets for a lottery * @param _lotteryId: lottery id * @param _ticketIds: array of ticket ids * @param _brackets: array of brackets for the ticket ids * @dev Callable by users only, not contract! */ function claimTickets( uint256 _lotteryId, uint256[] calldata _ticketIds, uint32[] calldata _brackets ) external override notContract nonReentrant { require(_ticketIds.length == _brackets.length, "Not same length"); require(_ticketIds.length != 0, "Length must be >0"); require( _ticketIds.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets" ); require( _lotteries[_lotteryId].status == Status.Claimable, "Lottery not claimable" ); // Initializes the rewardInBirbToTransfer uint256 rewardInBirbToTransfer; for (uint256 i = 0; i < _ticketIds.length; i++) { require(_brackets[i] < 6, "Bracket out of range"); // Must be between 0 and 5 uint256 thisTicketId = _ticketIds[i]; require( _lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high" ); require( _lotteries[_lotteryId].firstTicketId <= thisTicketId, "TicketId too low" ); require( msg.sender == _tickets[thisTicketId].owner, "Not the owner" ); // Update the lottery ticket owner to 0x address _tickets[thisTicketId].owner = address(0); uint256 rewardForTicketId = _calculateRewardsForTicketId( _lotteryId, thisTicketId, _brackets[i] ); // Check user is claiming the correct bracket require(rewardForTicketId != 0, "No prize for this bracket"); if (_brackets[i] != 5) { require( _calculateRewardsForTicketId( _lotteryId, thisTicketId, _brackets[i] + 1 ) == 0, "Bracket must be higher" ); } // Increment the reward to transfer rewardInBirbToTransfer += rewardForTicketId; } // Transfer money to msg.sender birbToken.safeTransfer(msg.sender, rewardInBirbToTransfer); emit TicketsClaim( msg.sender, rewardInBirbToTransfer, _lotteryId, _ticketIds.length ); } /** * @notice Close lottery * @param _lotteryId: lottery id * @dev Callable by operator */ function closeLottery(uint256 _lotteryId) external override onlyOperator nonReentrant { require( _lotteries[_lotteryId].status == Status.Open, "Lottery not open" ); require( block.timestamp > _lotteries[_lotteryId].endTime, "Lottery not over" ); _lotteries[_lotteryId].firstTicketIdNextLottery = currentTicketId; // Request a random number from the generator based on a seed randomGenerator.getRandomNumber( uint256(keccak256(abi.encodePacked(_lotteryId, currentTicketId))) ); _lotteries[_lotteryId].status = Status.Close; emit LotteryClose(_lotteryId, currentTicketId); } /** * @notice Draw the final number, calculate reward in BIRB per group, and make lottery claimable * @param _lotteryId: lottery id * @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all) * @dev Callable by operator */ function drawFinalNumberAndMakeLotteryClaimable( uint256 _lotteryId, bool _autoInjection ) external override onlyOperator nonReentrant { require( _lotteries[_lotteryId].status == Status.Close, "Lottery not close" ); require( _lotteryId == randomGenerator.viewLatestLotteryId(), "Numbers not drawn" ); // Calculate the finalNumber based on the randomResult generated by ChainLink's fallback uint32 finalNumber = randomGenerator.viewRandomResult(); // Initialize a number to count addresses in the previous bracket uint256 numberAddressesInPreviousBracket; // Calculate the amount to share post-treasury fee uint256 amountToShareToWinners = ( ((_lotteries[_lotteryId].amountCollectedInBirb) * (10000 - _lotteries[_lotteryId].treasuryFee)) ) / 10000; // Initializes the amount to withdraw to treasury uint256 amountToWithdrawToTreasury; // Calculate prizes in BIRB for each bracket by starting from the highest one for (uint32 i = 0; i < 6; i++) { uint32 j = 5 - i; uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1))); _lotteries[_lotteryId].countWinnersPerBracket[j] = _numberTicketsPerLotteryId[_lotteryId][ transformedWinningNumber ] - numberAddressesInPreviousBracket; // A. If number of users for this _bracket number is superior to 0 if ( (_numberTicketsPerLotteryId[_lotteryId][ transformedWinningNumber ] - numberAddressesInPreviousBracket) != 0 ) { // B. If rewards at this bracket are > 0, calculate, else, report the numberAddresses from previous bracket if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) { _lotteries[_lotteryId].birbPerBracket[j] = ((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / (_numberTicketsPerLotteryId[_lotteryId][ transformedWinningNumber ] - numberAddressesInPreviousBracket)) / 10000; // Update numberAddressesInPreviousBracket numberAddressesInPreviousBracket = _numberTicketsPerLotteryId[ _lotteryId ][transformedWinningNumber]; } // A. No BIRB to distribute, they are added to the amount to withdraw to treasury address } else { _lotteries[_lotteryId].birbPerBracket[j] = 0; amountToWithdrawToTreasury += (_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / 10000; } } // Update internal statuses for lottery _lotteries[_lotteryId].finalNumber = finalNumber; _lotteries[_lotteryId].status = Status.Claimable; if (_autoInjection) { pendingInjectionNextLottery = amountToWithdrawToTreasury; amountToWithdrawToTreasury = 0; } amountToWithdrawToTreasury = amountToWithdrawToTreasury.add( _lotteries[_lotteryId].amountCollectedInBirb.sub( amountToShareToWinners ) ); // Transfer BIRB to treasury address if (amountToWithdrawToTreasury > 0) { birbToken.safeTransfer(treasuryAddress, amountToWithdrawToTreasury); } emit LotteryNumberDrawn( currentLotteryId, finalNumber, numberAddressesInPreviousBracket ); } /** * @notice Change the random generator * @dev The calls to functions are used to verify the new generator implements them properly. * It is necessary to wait for the VRF response before starting a round. * Callable only by the contract owner * @param _randomGeneratorAddress: address of the random generator */ function changeRandomGenerator(address _randomGeneratorAddress) external onlyOwner { require( _lotteries[currentLotteryId].status == Status.Claimable, "Lottery not in claimable" ); // Request a random number from the generator based on a seed IRandomNumberGenerator(_randomGeneratorAddress).getRandomNumber( uint256( keccak256(abi.encodePacked(currentLotteryId, currentTicketId)) ) ); // Calculate the finalNumber based on the randomResult generated by ChainLink's fallback IRandomNumberGenerator(_randomGeneratorAddress).viewRandomResult(); randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress); emit NewRandomGenerator(_randomGeneratorAddress); } /** * @notice Inject funds * @param _lotteryId: lottery id * @param _amount: amount to inject in BIRB token * @dev Callable by owner or injector address */ function injectFunds(uint256 _lotteryId, uint256 _amount) external override onlyOwnerOrInjector { require( _lotteries[_lotteryId].status == Status.Open, "Lottery not open" ); uint256 balanceBefore = birbToken.balanceOf(address(this)); birbToken.safeTransferFrom(address(msg.sender), address(this), _amount); _amount = birbToken.balanceOf(address(this)).sub(balanceBefore); _lotteries[_lotteryId].amountCollectedInBirb = _lotteries[_lotteryId] .amountCollectedInBirb .add(_amount); emit LotteryInjection(_lotteryId, _amount); } /** * @notice Start the lottery * @dev Callable by operator * @param _endTime: endTime of the lottery * @param _priceTicketInBirb: price of a ticket in BIRB * @param _discountDivisor: the divisor to calculate the discount magnitude for bulks * @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000) * @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%) */ function startLottery( uint256 _endTime, uint256 _priceTicketInBirb, uint256 _discountDivisor, uint256[6] calldata _rewardsBreakdown, uint256 _treasuryFee ) external override onlyOperator { require( (currentLotteryId == 0) || (_lotteries[currentLotteryId].status == Status.Claimable), "Not time to start lottery" ); require( _endTime > block.timestamp && (_endTime.sub(block.timestamp) > MIN_LENGTH_LOTTERY) && (_endTime.sub(block.timestamp) < MAX_LENGTH_LOTTERY), "Lottery length outside of range" ); require( (_priceTicketInBirb >= minPriceTicketInBirb) && (_priceTicketInBirb <= maxPriceTicketInBirb), "Outside of limits" ); require( _discountDivisor >= MIN_DISCOUNT_DIVISOR, "Discount divisor too low" ); require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high"); require( _rewardsBreakdown[0] .add(_rewardsBreakdown[1]) .add(_rewardsBreakdown[2]) .add(_rewardsBreakdown[3]) .add(_rewardsBreakdown[4]) .add(_rewardsBreakdown[5]) == 10000, "Rewards must equal 10000" ); currentLotteryId = currentLotteryId.add(1); _lotteries[currentLotteryId] = Lottery({ status: Status.Open, startTime: block.timestamp, endTime: _endTime, priceTicketInBirb: _priceTicketInBirb, discountDivisor: _discountDivisor, rewardsBreakdown: _rewardsBreakdown, treasuryFee: _treasuryFee, birbPerBracket: [ uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0) ], countWinnersPerBracket: [ uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0) ], firstTicketId: currentTicketId, firstTicketIdNextLottery: currentTicketId, amountCollectedInBirb: pendingInjectionNextLottery, finalNumber: 0 }); emit LotteryOpen( currentLotteryId, block.timestamp, _endTime, _priceTicketInBirb, currentTicketId, pendingInjectionNextLottery ); pendingInjectionNextLottery = 0; } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of token amount to withdraw * @dev Only callable by owner. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(birbToken), "Cannot be BIRB token"); IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /** * @notice Set BIRB price ticket upper/lower limit * @dev Only callable by owner * @param _minPriceTicketInBirb: minimum price of a ticket in BIRB * @param _maxPriceTicketInBirb: maximum price of a ticket in BIRB */ function setMinAndMaxTicketPriceInBirb( uint256 _minPriceTicketInBirb, uint256 _maxPriceTicketInBirb ) external onlyOwner { require( _minPriceTicketInBirb <= _maxPriceTicketInBirb, "minPrice must be < maxPrice" ); minPriceTicketInBirb = _minPriceTicketInBirb; maxPriceTicketInBirb = _maxPriceTicketInBirb; } /** * @notice Set max number of tickets * @dev Only callable by owner */ function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner { require(_maxNumberTicketsPerBuy != 0, "Must be > 0"); maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy; } /** * @notice Set operator, treasury, and injector addresses * @dev Only callable by owner * @param _operatorAddress: address of the operator * @param _treasuryAddress: address of the treasury * @param _injectorAddress: address of the injector */ function setOperatorAndTreasuryAndInjectorAddresses( address _operatorAddress, address _treasuryAddress, address _injectorAddress ) external onlyOwner { require(_operatorAddress != address(0), "Cannot be zero address"); require(_treasuryAddress != address(0), "Cannot be zero address"); require(_injectorAddress != address(0), "Cannot be zero address"); operatorAddress = _operatorAddress; treasuryAddress = _treasuryAddress; injectorAddress = _injectorAddress; emit NewOperatorAndTreasuryAndInjectorAddresses( _operatorAddress, _treasuryAddress, _injectorAddress ); } /** * @notice Calculate price of a set of tickets * @param _discountDivisor: divisor for the discount * @param _priceTicket price of a ticket (in BIRB) * @param _numberTickets number of tickets to buy */ function calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets ) external pure returns (uint256) { require( _discountDivisor >= MIN_DISCOUNT_DIVISOR, "Must be >= MIN_DISCOUNT_DIVISOR" ); require(_numberTickets != 0, "Number of tickets must be > 0"); return _calculateTotalPriceForBulkTickets( _discountDivisor, _priceTicket, _numberTickets ); } /** * @notice View current lottery id */ function viewCurrentLotteryId() external view override returns (uint256) { return currentLotteryId; } /** * @notice View lottery information * @param _lotteryId: lottery id */ function viewLottery(uint256 _lotteryId) external view returns (Lottery memory) { return _lotteries[_lotteryId]; } /** * @notice View ticker statuses and numbers for an array of ticket ids * @param _ticketIds: array of _ticketId */ function viewNumbersAndStatusesForTicketIds(uint256[] calldata _ticketIds) external view returns (uint32[] memory, bool[] memory) { uint256 length = _ticketIds.length; uint32[] memory ticketNumbers = new uint32[](length); bool[] memory ticketStatuses = new bool[](length); for (uint256 i = 0; i < length; i++) { ticketNumbers[i] = _tickets[_ticketIds[i]].number; if (_tickets[_ticketIds[i]].owner == address(0)) { ticketStatuses[i] = true; } else { ticketStatuses[i] = false; } } return (ticketNumbers, ticketStatuses); } /** * @notice View rewards for a given ticket, providing a bracket, and lottery id * @dev Computations are mostly offchain. This is used to verify a ticket! * @param _lotteryId: lottery id * @param _ticketId: ticket id * @param _bracket: bracket for the ticketId to verify the claim and calculate rewards */ function viewRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket ) external view returns (uint256) { // Check lottery is in claimable status if (_lotteries[_lotteryId].status != Status.Claimable) { return 0; } // Check ticketId is within range if ( (_lotteries[_lotteryId].firstTicketIdNextLottery < _ticketId) && (_lotteries[_lotteryId].firstTicketId >= _ticketId) ) { return 0; } return _calculateRewardsForTicketId(_lotteryId, _ticketId, _bracket); } /** * @notice View user ticket ids, numbers, and statuses of user for a given lottery * @param _user: user address * @param _lotteryId: lottery id * @param _cursor: cursor to start where to retrieve the tickets * @param _size: the number of tickets to retrieve */ function viewUserInfoForLotteryId( address _user, uint256 _lotteryId, uint256 _cursor, uint256 _size ) external view returns ( uint256[] memory, uint32[] memory, bool[] memory, uint256 ) { uint256 length = _size; uint256 numberTicketsBoughtAtLotteryId = _userTicketIdsPerLotteryId[ _user ][_lotteryId].length; if (length > numberTicketsBoughtAtLotteryId.sub(_cursor)) { length = numberTicketsBoughtAtLotteryId.sub(_cursor); } uint256[] memory lotteryTicketIds = new uint256[](length); uint32[] memory ticketNumbers = new uint32[](length); bool[] memory ticketStatuses = new bool[](length); for (uint256 i = 0; i < length; i++) { lotteryTicketIds[i] = _userTicketIdsPerLotteryId[_user][_lotteryId][ i.add(_cursor) ]; ticketNumbers[i] = _tickets[lotteryTicketIds[i]].number; // True = ticket claimed if (_tickets[lotteryTicketIds[i]].owner == address(0)) { ticketStatuses[i] = true; } else { // ticket not claimed (includes the ones that cannot be claimed) ticketStatuses[i] = false; } } return ( lotteryTicketIds, ticketNumbers, ticketStatuses, _cursor.add(length) ); } /** * @notice Calculate rewards for a given ticket * @param _lotteryId: lottery id * @param _ticketId: ticket id * @param _bracket: bracket for the ticketId to verify the claim and calculate rewards */ function _calculateRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket ) internal view returns (uint256) { // Retrieve the winning number combination uint32 userNumber = _lotteries[_lotteryId].finalNumber; // Retrieve the user number combination from the ticketId uint32 winningTicketNumber = _tickets[_ticketId].number; // Apply transformation to verify the claim provided by the user is true uint32 transformedWinningNumber = _bracketCalculator[_bracket] + (winningTicketNumber % (uint32(10)**(_bracket + 1))); uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1))); // Confirm that the two transformed numbers are the same, if not throw if (transformedWinningNumber == transformedUserNumber) { return _lotteries[_lotteryId].birbPerBracket[_bracket]; } else { return 0; } } /** * @notice Calculate final price for bulk of tickets * @param _discountDivisor: divisor for the discount (the smaller it is, the greater the discount is) * @param _priceTicket: price of a ticket * @param _numberTickets: number of tickets purchased */ function _calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets ) internal pure returns (uint256) { return (_priceTicket * _numberTickets * (_discountDivisor + 1 - _numberTickets)) / _discountDivisor; } /** * @notice Check if an address is a contract */ function _isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } }
It allows the admin to recover wrong tokens sent to the contract _tokenAddress: the address of the token to withdraw _tokenAmount: the number of token amount to withdraw Only callable by owner./
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(birbToken), "Cannot be BIRB token"); IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); }
12,751,304
pragma solidity ^0.4.23; /* * NamiMultiSigWallet smart contract------------------------------- */ /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. contract NamiMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { // Transaction tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } } /* * Contract that is working with ERC223 tokens */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success); function tokenFallbackBuyer(address _from, uint _value, address _buyer) public returns (bool success); function tokenFallbackExchange(address _from, uint _value, uint _price) public returns (bool success); } contract PresaleToken { mapping (address => uint256) public balanceOf; function burnTokens(address _owner) public; } // ERC20 token interface is implemented only partially. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract NamiCrowdSale { using SafeMath for uint256; /// NAC Broker Presale Token /// @dev Constructor constructor(address _escrow, address _namiMultiSigWallet, address _namiPresale) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; namiPresale = _namiPresale; } /*/ * Constants /*/ string public name = "Nami ICO"; string public symbol = "NAC"; uint public decimals = 18; bool public TRANSFERABLE = false; // default not transferable uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei); uint public binary = 0; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; // nami presale contract address public namiPresale; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; // binary option address address public binaryAddress; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; modifier onlyCrowdsaleManager() { require(msg.sender == crowdsaleManager); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyTranferable() { require(TRANSFERABLE); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); // Log migrate token event LogMigrate(address _from, address _to, uint256 amount); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } // Transfer the balance from owner&#39;s account to another account // only escrow can send token (to send token private sale) function transferForTeam(address _to, uint256 _value) public onlyEscrow { _transfer(msg.sender, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyTranferable { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyTranferable returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyTranferable returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // allows transfer token function changeTransferable () public onlyEscrow { TRANSFERABLE = !TRANSFERABLE; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change binary value function changeBinary(uint _binary) public onlyEscrow { binary = _binary; } // change binary address function changeBinaryAddress(address _binaryAddress) public onlyEscrow { require(_binaryAddress != 0x0); binaryAddress = _binaryAddress; } /* * price in ICO: * first week: 1 ETH = 2400 NAC * second week: 1 ETH = 23000 NAC * 3rd week: 1 ETH = 2200 NAC * 4th week: 1 ETH = 2100 NAC * 5th week: 1 ETH = 2000 NAC * 6th week: 1 ETH = 1900 NAC * 7th week: 1 ETH = 1800 NAC * 8th week: 1 ETH = 1700 nac * time: * 1517443200: Thursday, February 1, 2018 12:00:00 AM * 1518048000: Thursday, February 8, 2018 12:00:00 AM * 1518652800: Thursday, February 15, 2018 12:00:00 AM * 1519257600: Thursday, February 22, 2018 12:00:00 AM * 1519862400: Thursday, March 1, 2018 12:00:00 AM * 1520467200: Thursday, March 8, 2018 12:00:00 AM * 1521072000: Thursday, March 15, 2018 12:00:00 AM * 1521676800: Thursday, March 22, 2018 12:00:00 AM * 1522281600: Thursday, March 29, 2018 12:00:00 AM */ function getPrice() public view returns (uint price) { if (now < 1517443200) { // presale return 3450; } else if (1517443200 < now && now <= 1518048000) { // 1st week return 2400; } else if (1518048000 < now && now <= 1518652800) { // 2nd week return 2300; } else if (1518652800 < now && now <= 1519257600) { // 3rd week return 2200; } else if (1519257600 < now && now <= 1519862400) { // 4th week return 2100; } else if (1519862400 < now && now <= 1520467200) { // 5th week return 2000; } else if (1520467200 < now && now <= 1521072000) { // 6th week return 1900; } else if (1521072000 < now && now <= 1521676800) { // 7th week return 1800; } else if (1521676800 < now && now <= 1522281600) { // 8th week return 1700; } else { return binary; } } function() payable public { buy(msg.sender); } function buy(address _buyer) payable public { // Available only if presale is running. require(currentPhase == Phase.Running); // require ICO time or binary option require(now <= 1522281600 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); // add new token to buyer balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); // add new token to totalSupply totalSupply = totalSupply.add(newTokens); emit LogBuy(_buyer,newTokens); emit Transfer(this,_buyer,newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase require(currentPhase == Phase.Migrating); uint tokens = balanceOf[_owner]; require(tokens != 0); balanceOf[_owner] = 0; totalSupply -= tokens; emit LogBurn(_owner, tokens); emit Transfer(_owner, crowdsaleManager, tokens); // Automatically switch phase when migration is done. if (totalSupply == 0) { currentPhase = Phase.Migrated; emit LogPhaseSwitch(Phase.Migrated); } } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyEscrow { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); require(canSwitchPhase); currentPhase = _nextPhase; emit LogPhaseSwitch(_nextPhase); } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } function setCrowdsaleManager(address _mgr) public onlyEscrow { // You can&#39;t change crowdsale contract when migration is in progress. require(currentPhase != Phase.Migrating); crowdsaleManager = _mgr; } // internal migrate migration tokens function _migrateToken(address _from, address _to) internal { PresaleToken presale = PresaleToken(namiPresale); uint256 newToken = presale.balanceOf(_from); require(newToken > 0); // burn old token presale.burnTokens(_from); // add new token to _to balanceOf[_to] = balanceOf[_to].add(newToken); // add new token to totalSupply totalSupply = totalSupply.add(newToken); emit LogMigrate(_from, _to, newToken); emit Transfer(this,_to,newToken); } // migate token function for Nami Team function migrateToken(address _from, address _to) public onlyEscrow { _migrateToken(_from, _to); } // migrate token for investor function migrateForInvestor() public { _migrateToken(msg.sender, msg.sender); } // Nami internal exchange // event for Nami exchange event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller); event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price); /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackExchange` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackExchange` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _price price to sell token. */ function transferToExchange(address _to, uint _value, uint _price) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackExchange(msg.sender, _value, _price); emit TransferToExchange(msg.sender, _to, _value, _price); } } /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackBuyer` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackBuyer` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _buyer address of seller. */ function transferToBuyer(address _to, uint _value, address _buyer) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackBuyer(msg.sender, _value, _buyer); emit TransferToBuyer(msg.sender, _to, _value, _buyer); } } //------------------------------------------------------------------------------------------------------- } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract NamiTrade{ using SafeMath for uint256; uint public minNac = 0; // min NAC deposit uint public minWithdraw = 10 * 10**18; uint public maxWithdraw = 1000000 * 10**18; // max NAC withdraw one time constructor(address _escrow, address _namiMultiSigWallet, address _namiAddress) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; NamiAddr = _namiAddress; } // balance of pool uint public NetfBalance; /** * NetfRevenueBalance: NetfRevenue[_roundIndex].currentNAC * NlfBalance: NLFunds[currentRound].currentNAC * NlfRevenueBalance: listSubRoundNLF[currentRound][_subRoundIndex].totalNacInSubRound */ // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; /// address of Nami token address public NamiAddr; modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyNami { require(msg.sender == NamiAddr); _; } modifier onlyNamiMultisig { require(msg.sender == namiMultiSigWallet); _; } modifier onlyController { require(isController[msg.sender] == true); _; } /* * * list setting function */ mapping(address => bool) public isController; // set controller address /** * make new controller * require input address is not a controller * execute any time in sc state */ function setController(address _controller) public onlyEscrow { require(!isController[_controller]); isController[_controller] = true; } /** * remove controller * require input address is a controller * execute any time in sc state */ function removeController(address _controller) public onlyEscrow { require(isController[_controller]); isController[_controller] = false; } // change minimum nac to deposit function changeMinNac(uint _minNAC) public onlyEscrow { require(_minNAC != 0); minNac = _minNAC; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // min and max for withdraw nac function changeMinWithdraw(uint _minWithdraw) public onlyEscrow { require(_minWithdraw != 0); minWithdraw = _minWithdraw; } function changeMaxWithdraw(uint _maxNac) public onlyEscrow { require(_maxNac != 0); maxWithdraw = _maxNac; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev withdraw NAC to nami multisignature wallet, only escrow can call /// @param _amount value NAC to withdraw function withdrawNac(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); if (namiToken.balanceOf(address(this)) > 0) { namiToken.transfer(namiMultiSigWallet, _amount); } } /* * * * List event */ event Deposit(address indexed user, uint amount, uint timeDeposit); event Withdraw(address indexed user, uint amount, uint timeWithdraw); event PlaceBuyFciOrder(address indexed investor, uint amount, uint timePlaceOrder); event PlaceSellFciOrder(address indexed investor, uint amount, uint timePlaceOrder); event InvestToNLF(address indexed investor, uint amount, uint timeInvest); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////fci token function/////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// string public name = "Nami Trade"; string public symbol = "FCI-Test"; uint8 public decimals = 18; uint256 public totalSupply; // paus phrase to compute ratio fci bool public isPause; // time expires of price fci uint256 public timeExpires; // price fci : if 1 fci = 2 nac => priceFci = 2000000 uint public fciDecimals = 1000000; uint256 public priceFci; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); // This notifies someone buy fci by NAC event BuyFci(address investor, uint256 valueNac, uint256 valueFci, uint timeBuyFci); event SellFci(address investor, uint256 valueNac, uint256 valueFci, uint timeSellFci); modifier onlyRunning { require(isPause == false); _; } /** * controller update balance of Netf to smart contract */ function addNacToNetf(uint _valueNac) public onlyController { NetfBalance = NetfBalance.add(_valueNac); } /** * controller update balance of Netf to smart contract */ function removeNacFromNetf(uint _valueNac) public onlyController { NetfBalance = NetfBalance.sub(_valueNac); } //////////////////////////////////////////////////////buy and sell fci function////////////////////////////////////////////////////////// /** * Setup pause phrase */ function changePause() public onlyController { isPause = !isPause; } /** * * * update price fci daily */ function updatePriceFci(uint _price, uint _timeExpires) onlyController public { require(now > timeExpires); priceFci = _price; timeExpires = _timeExpires; } /** * before buy users need to place buy Order * function buy fci * only controller can execute in phrase running */ function buyFci(address _buyer, uint _valueNac) onlyController public { // require fci is Running require(isPause == false && now < timeExpires); // require buyer not is 0x0 address require(_buyer != 0x0); require( _valueNac * fciDecimals > priceFci); uint fciReceive = (_valueNac.mul(fciDecimals))/priceFci; // construct fci balanceOf[_buyer] = balanceOf[_buyer].add(fciReceive); totalSupply = totalSupply.add(fciReceive); NetfBalance = NetfBalance.add(_valueNac); emit Transfer(address(this), _buyer, fciReceive); emit BuyFci(_buyer, _valueNac, fciReceive, now); } /** * * before controller buy fci for user * user nead to place sell order */ function placeSellFciOrder(uint _valueFci) onlyRunning public { require(balanceOf[msg.sender] >= _valueFci && _valueFci > 0); _transfer(msg.sender, address(this), _valueFci); emit PlaceSellFciOrder(msg.sender, _valueFci, now); } /** * * function sellFci * only controller can execute in phare running */ function sellFci(address _seller, uint _valueFci) onlyController public { // require fci is Running require(isPause == false && now < timeExpires); // require buyer not is 0x0 address require(_seller != 0x0); require(_valueFci * priceFci > fciDecimals); uint nacReturn = (_valueFci.mul(priceFci))/fciDecimals; // destroy fci balanceOf[address(this)] = balanceOf[address(this)].sub(_valueFci); totalSupply = totalSupply.sub(_valueFci); // update NETF balance NetfBalance = NetfBalance.sub(nacReturn); // send NAC NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); namiToken.transfer(_seller, nacReturn); emit Transfer(_seller, address(this), _valueFci); emit SellFci(_seller, nacReturn, _valueFci, now); } /////////////////////////////////////////////////////NETF Revenue function/////////////////////////////////////////////////////////////// struct ShareHolderNETF { uint stake; bool isWithdrawn; } struct RoundNetfRevenue { bool isOpen; uint currentNAC; uint totalFci; bool withdrawable; } uint public currentNetfRound; mapping (uint => RoundNetfRevenue) public NetfRevenue; mapping (uint => mapping(address => ShareHolderNETF)) public usersNETF; // 1. open Netf round /** * first controller open one round for netf revenue */ function openNetfRevenueRound(uint _roundIndex) onlyController public { require(NetfRevenue[_roundIndex].isOpen == false); currentNetfRound = _roundIndex; NetfRevenue[_roundIndex].isOpen = true; } /** * * this function update balance of NETF revenue funds add NAC to funds * only executable if round open and round not withdraw yet */ function depositNetfRevenue(uint _valueNac) onlyController public { require(NetfRevenue[currentNetfRound].isOpen == true && NetfRevenue[currentNetfRound].withdrawable == false); NetfRevenue[currentNetfRound].currentNAC = NetfRevenue[currentNetfRound].currentNAC.add(_valueNac); } /** * * this function update balance of NETF Funds remove NAC from funds * only executable if round open and round not withdraw yet */ function withdrawNetfRevenue(uint _valueNac) onlyController public { require(NetfRevenue[currentNetfRound].isOpen == true && NetfRevenue[currentNetfRound].withdrawable == false); NetfRevenue[currentNetfRound].currentNAC = NetfRevenue[currentNetfRound].currentNAC.sub(_valueNac); } // switch to pause phrase here /** * after pause all investor to buy, sell and exchange fci on the market * controller or investor latch final fci of current round */ function latchTotalFci(uint _roundIndex) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); require(NetfRevenue[_roundIndex].withdrawable == false); NetfRevenue[_roundIndex].totalFci = totalSupply; } function latchFciUserController(uint _roundIndex, address _investor) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); require(NetfRevenue[_roundIndex].withdrawable == false); require(balanceOf[_investor] > 0); usersNETF[_roundIndex][_investor].stake = balanceOf[_investor]; } /** * investor can latch Fci by themself */ function latchFciUser(uint _roundIndex) public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); require(NetfRevenue[_roundIndex].withdrawable == false); require(balanceOf[msg.sender] > 0); usersNETF[_roundIndex][msg.sender].stake = balanceOf[msg.sender]; } /** * after all investor latch fci, controller change round state withdrawable * now investor can withdraw NAC from NetfRevenue funds of this round * and auto switch to unpause phrase */ function changeWithdrawableNetfRe(uint _roundIndex) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); NetfRevenue[_roundIndex].withdrawable = true; isPause = false; } // after latch all investor, unpause here /** * withdraw NAC for * run by controller */ function withdrawNacNetfReController(uint _roundIndex, address _investor) onlyController public { require(NetfRevenue[_roundIndex].withdrawable == true && isPause == false && _investor != 0x0); require(usersNETF[_roundIndex][_investor].stake > 0 && usersNETF[_roundIndex][_investor].isWithdrawn == false); require(NetfRevenue[_roundIndex].totalFci > 0); // withdraw NAC uint nacReturn = ( NetfRevenue[_roundIndex].currentNAC.mul(usersNETF[_roundIndex][_investor].stake) ) / NetfRevenue[_roundIndex].totalFci; NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); namiToken.transfer(_investor, nacReturn); usersNETF[_roundIndex][_investor].isWithdrawn = true; } /** * withdraw NAC for * run by investor */ function withdrawNacNetfRe(uint _roundIndex) public { require(NetfRevenue[_roundIndex].withdrawable == true && isPause == false); require(usersNETF[_roundIndex][msg.sender].stake > 0 && usersNETF[_roundIndex][msg.sender].isWithdrawn == false); require(NetfRevenue[_roundIndex].totalFci > 0); // withdraw NAC uint nacReturn = ( NetfRevenue[_roundIndex].currentNAC.mul(usersNETF[_roundIndex][msg.sender].stake) ) / NetfRevenue[_roundIndex].totalFci; NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); namiToken.transfer(msg.sender, nacReturn); usersNETF[_roundIndex][msg.sender].isWithdrawn = true; } /////////////////////////////////////////////////////token fci function////////////////////////////////////////////////////////////////// /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyRunning { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyRunning returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyRunning returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyRunning returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////end fci token function/////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////pool function//////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// uint public currentRound = 1; uint public currentSubRound = 1; struct shareHolderNLF { uint fciNLF; bool isWithdrawnRound; } struct SubRound { uint totalNacInSubRound; bool isOpen; bool isCloseNacPool; } struct Round { bool isOpen; bool isActivePool; bool withdrawable; uint currentNAC; uint finalNAC; } // NLF Funds mapping(uint => Round) public NLFunds; mapping(uint => mapping(address => mapping(uint => bool))) public isWithdrawnSubRoundNLF; mapping(uint => mapping(uint => SubRound)) public listSubRoundNLF; mapping(uint => mapping(address => shareHolderNLF)) public membersNLF; event ActivateRound(uint RoundIndex, uint TimeActive); event ActivateSubRound(uint RoundIndex, uint TimeActive); // ------------------------------------------------ /** * Admin function * Open and Close Round */ function activateRound(uint _roundIndex) onlyEscrow public { // require round not open require(NLFunds[_roundIndex].isOpen == false); NLFunds[_roundIndex].isOpen = true; currentRound = _roundIndex; emit ActivateRound(_roundIndex, now); } ///////////////////////deposit to NLF funds in tokenFallbackExchange/////////////////////////////// /** * after all user deposit to NLF pool */ function deactivateRound(uint _roundIndex) onlyEscrow public { // require round id is openning require(NLFunds[_roundIndex].isOpen == true); NLFunds[_roundIndex].isActivePool = true; NLFunds[_roundIndex].isOpen = false; NLFunds[_roundIndex].finalNAC = NLFunds[_roundIndex].currentNAC; } /** * before send NAC to subround controller need active subround */ function activateSubRound(uint _subRoundIndex) onlyController public { // require current round is not open and pool active require(NLFunds[currentRound].isOpen == false && NLFunds[currentRound].isActivePool == true); // require sub round not open require(listSubRoundNLF[currentRound][_subRoundIndex].isOpen == false); // currentSubRound = _subRoundIndex; require(listSubRoundNLF[currentRound][_subRoundIndex].isCloseNacPool == false); listSubRoundNLF[currentRound][_subRoundIndex].isOpen = true; emit ActivateSubRound(_subRoundIndex, now); } /** * every week controller deposit to subround to send NAC to all user have NLF fci */ function depositToSubRound(uint _value) onlyController public { // require sub round is openning require(currentSubRound != 0); require(listSubRoundNLF[currentRound][currentSubRound].isOpen == true); require(listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool == false); // modify total NAC in each subround listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound = listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound.add(_value); } /** * every week controller deposit to subround to send NAC to all user have NLF fci */ function withdrawFromSubRound(uint _value) onlyController public { // require sub round is openning require(currentSubRound != 0); require(listSubRoundNLF[currentRound][currentSubRound].isOpen == true); require(listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool == false); // modify total NAC in each subround listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound = listSubRoundNLF[currentRound][currentSubRound].totalNacInSubRound.sub(_value); } /** * controller close deposit subround phrase and user can withdraw NAC from subround */ function closeDepositSubRound() onlyController public { require(listSubRoundNLF[currentRound][currentSubRound].isOpen == true); require(listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool == false); listSubRoundNLF[currentRound][currentSubRound].isCloseNacPool = true; } /** * user withdraw NAC from each subround of NLF funds for investor */ function withdrawSubRound(uint _subRoundIndex) public { // require close deposit to subround require(listSubRoundNLF[currentRound][_subRoundIndex].isCloseNacPool == true); // user not ever withdraw nac in this subround require(isWithdrawnSubRoundNLF[currentRound][msg.sender][_subRoundIndex] == false); // require user have fci require(membersNLF[currentRound][msg.sender].fciNLF > 0); // withdraw token NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn = (listSubRoundNLF[currentRound][_subRoundIndex].totalNacInSubRound.mul(membersNLF[currentRound][msg.sender].fciNLF)).div(NLFunds[currentRound].finalNAC); namiToken.transfer(msg.sender, nacReturn); isWithdrawnSubRoundNLF[currentRound][msg.sender][_subRoundIndex] = true; } /** * controller of NLF add NAC to update NLF balance * this NAC come from 10% trading revenue */ function addNacToNLF(uint _value) public onlyController { require(NLFunds[currentRound].isActivePool == true); require(NLFunds[currentRound].withdrawable == false); NLFunds[currentRound].currentNAC = NLFunds[currentRound].currentNAC.add(_value); } /** * controller get NAC from NLF pool to send to trader */ function removeNacFromNLF(uint _value) public onlyController { require(NLFunds[currentRound].isActivePool == true); require(NLFunds[currentRound].withdrawable == false); NLFunds[currentRound].currentNAC = NLFunds[currentRound].currentNAC.sub(_value); } /** * end of round escrow run this to allow user sell fci to receive NAC */ function changeWithdrawableRound(uint _roundIndex) public onlyEscrow { require(NLFunds[currentRound].isActivePool == true); require(NLFunds[_roundIndex].withdrawable == false && NLFunds[_roundIndex].isOpen == false); NLFunds[_roundIndex].withdrawable = true; } /** * end of round user sell fci to receive NAC from NLF funds * function for investor */ function withdrawRound(uint _roundIndex) public { require(NLFunds[_roundIndex].withdrawable == true); require(membersNLF[currentRound][msg.sender].isWithdrawnRound == false); require(membersNLF[currentRound][msg.sender].fciNLF > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn = NLFunds[currentRound].currentNAC.mul(membersNLF[currentRound][msg.sender].fciNLF).div(NLFunds[currentRound].finalNAC); namiToken.transfer(msg.sender, nacReturn); // update status round membersNLF[currentRound][msg.sender].isWithdrawnRound = true; membersNLF[currentRound][msg.sender].fciNLF = 0; } function withdrawRoundController(uint _roundIndex, address _investor) public onlyController { require(NLFunds[_roundIndex].withdrawable == true); require(membersNLF[currentRound][_investor].isWithdrawnRound == false); require(membersNLF[currentRound][_investor].fciNLF > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn = NLFunds[currentRound].currentNAC.mul(membersNLF[currentRound][_investor].fciNLF).div(NLFunds[currentRound].finalNAC); namiToken.transfer(msg.sender, nacReturn); // update status round membersNLF[currentRound][_investor].isWithdrawnRound = true; membersNLF[currentRound][_investor].fciNLF = 0; } /** * fall back function call from nami crawsale smart contract * deposit NAC to NAMI TRADE broker, invest to NETF and NLF funds */ function tokenFallbackExchange(address _from, uint _value, uint _choose) onlyNami public returns (bool success) { require(_choose <= 2); if (_choose == 0) { // deposit NAC to nami trade broker require(_value >= minNac); emit Deposit(_from, _value, now); } else if(_choose == 1) { require(_value >= minNac && NLFunds[currentRound].isOpen == true); // invest to NLF funds membersNLF[currentRound][_from].fciNLF = membersNLF[currentRound][_from].fciNLF.add(_value); NLFunds[currentRound].currentNAC = NLFunds[currentRound].currentNAC.add(_value); emit InvestToNLF(_from, _value, now); } else if(_choose == 2) { // invest NAC to NETF Funds require(_value >= minNac); // msg.value >= 0.1 ether emit PlaceBuyFciOrder(_from, _value, now); } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////end pool function/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // withdraw token function withdrawToken(address _account, uint _amount) public onlyController { require(_amount >= minWithdraw && _amount <= maxWithdraw); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(address(this)); require(previousBalances >= _amount); // transfer token namiToken.transfer(_account, _amount); // emit event emit Withdraw(_account, _amount, now); assert(previousBalances >= namiToken.balanceOf(address(this))); } }
end of round user sell fci to receive NAC from NLF funds function for investor/ update status round
function withdrawRound(uint _roundIndex) public { require(NLFunds[_roundIndex].withdrawable == true); require(membersNLF[currentRound][msg.sender].isWithdrawnRound == false); require(membersNLF[currentRound][msg.sender].fciNLF > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn = NLFunds[currentRound].currentNAC.mul(membersNLF[currentRound][msg.sender].fciNLF).div(NLFunds[currentRound].finalNAC); namiToken.transfer(msg.sender, nacReturn); membersNLF[currentRound][msg.sender].isWithdrawnRound = true; membersNLF[currentRound][msg.sender].fciNLF = 0; }
2,024,916
./full_match/3/0x3FC62b0F0Bb09D58578047587A76e98d531D522B/sources/brycefinalcode.sol
See {IERC165-supportsInterface}./
function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
8,160,822
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract CryptoonGoonzSketches is ERC721Enumerable, IERC2981, ERC721URIStorage, ERC721Burnable, Ownable { using Counters for Counters.Counter; Counters.Counter private tokenIdCounter; string private baseURI; address private storeOwner; address private proxyRegistryAddress; bool public isOpenSeaProxyActive = true; uint16 public constant MAX_SUPPLY = 140; constructor( string memory _name, string memory _symbol, address _storeOwner, address _proxyRegistryAddress ) ERC721(_name, _symbol) { storeOwner = _storeOwner; proxyRegistryAddress = _proxyRegistryAddress; setBaseURI("ipfs://"); tokenIdCounter.increment(); } function mint(string memory _tokenURI) public onlyOwners { _mintTo(msg.sender, _tokenURI); } function mintTo(address _recipient, string memory _tokenURI) public onlyOwners { _mintTo(_recipient, _tokenURI); } function _mintTo(address _recipient, string memory _tokenURI) private { uint256 tokenId = tokenIdCounter.current(); require(tokenId <= MAX_SUPPLY, "Mint: max supply reached"); _safeMint(_recipient, tokenId); setTokenURI(tokenId, _tokenURI); tokenIdCounter.increment(); } function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwners { _setTokenURI(_tokenId, _tokenURI); } function setBaseURI(string memory baseURI_) public onlyOwners { baseURI = baseURI_; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev To disable OpenSea gasless listings proxy in case of an issue */ function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive) external onlyOwner { isOpenSeaProxyActive = _isOpenSeaProxyActive; } modifier onlyOwners() { require(owner() == _msgSender() || storeOwner == _msgSender(), "caller is not the contract or store owner"); _; } function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165, ERC721Enumerable) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @notice enable OpenSea gasless listings * @dev Overriding `isApprovedForAll` to allowlist user's OpenSea proxy accounts */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * @dev See {IERC165-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Nonexistent token"); return (address(this), SafeMath.div(SafeMath.mul(salePrice, 15), 200)); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT 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(); } } // SPDX-License-Identifier: MIT 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]; } } } // SPDX-License-Identifier: MIT 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 no longer needed starting with Solidity 0.8. 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; } } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT 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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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); } /** * @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); } /** * @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 of token that is not own"); 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); } /** * @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 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 {} } // SPDX-License-Identifier: MIT 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; } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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); } } } } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT 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 tokenId); /** * @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); }
See {IERC165-royaltyInfo}./
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Nonexistent token"); return (address(this), SafeMath.div(SafeMath.mul(salePrice, 15), 200)); }
14,642,121
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface Migratable { function migrateTo(address user, address token, uint256 amount) payable external; } /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } /** * @title Serializable Migration * @author Ben Huang * @notice Let migration support serialization and deserialization */ contract SerializableMigration { using SafeMath for uint256; using BytesLib for bytes; uint constant public MIGRATION_1_SIZE = 24; uint constant public TOKENID_SIZE = 2; uint constant public SIGNATURE_SIZE = 65; uint8 constant internal _MASK_IS_ETH = 0x01; /** * @notice Get target address from the serialized migration data * @param ser_data Serialized migration data * @return target Target contract address */ function _getMigrationTarget(bytes memory ser_data) internal pure returns (address target) { target = ser_data.toAddress(ser_data.length - 20); } /** * @notice Get user ID from the serialized migration data * @param ser_data Serialized migration data * @return userID User ID */ function _getMigrationUserID(bytes memory ser_data) internal pure returns (uint256 userID) { userID = ser_data.toUint32(ser_data.length - 24); } /** * @notice Get token count * @param ser_data Serialized migration data * @return n The migrate token amount */ function _getMigrationCount(bytes memory ser_data) internal pure returns (uint256 n) { n = (ser_data.length - SIGNATURE_SIZE - MIGRATION_1_SIZE) / 2; } /** * @notice Get token ID to be migrated * @param ser_data Serialized migration data * @param index The index of token ID to be migrated * @return tokenID The token ID to be migrated */ function _getMigrationTokenID(bytes memory ser_data, uint index) internal pure returns (uint256 tokenID) { require(index < _getMigrationCount(ser_data)); tokenID = ser_data.toUint16(ser_data.length - MIGRATION_1_SIZE - (TOKENID_SIZE.mul(index + 1))); } /** * @notice Get v from the serialized migration data * @param ser_data Serialized migration data * @return v Signature v */ function _getMigrationV(bytes memory ser_data) internal pure returns (uint8 v) { v = ser_data.toUint8(SIGNATURE_SIZE - 1); } /** * @notice Get r from the serialized migration data * @param ser_data Serialized migration data * @return r Signature r */ function _getMigrationR(bytes memory ser_data) internal pure returns (bytes32 r) { r = ser_data.toBytes32(SIGNATURE_SIZE - 33); } /** * @notice Get s from the serialized migration data * @param ser_data Serialized migration data * @return s Signature s */ function _getMigrationS(bytes memory ser_data) internal pure returns (bytes32 s) { s = ser_data.toBytes32(SIGNATURE_SIZE - 65); } /** * @notice Get hash from the serialized migration data * @param ser_data Serialized migration data * @return hash Migration hash without signature */ function _getMigrationHash(bytes memory ser_data) internal pure returns (bytes32 hash) { hash = keccak256(ser_data.slice(65, ser_data.length - SIGNATURE_SIZE)); } } /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ 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)); } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; 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)); } 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)); 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).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(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 equal true). * @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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } /** * @title Serializable Order * @author Ben Huang * @notice Let order support serialization and deserialization */ contract SerializableOrder { using SafeMath for uint256; using BytesLib for bytes; uint constant public ORDER_SIZE = 206; uint constant public UNSIGNED_ORDER_SIZE = 141; uint8 constant internal _MASK_IS_BUY = 0x01; uint8 constant internal _MASK_IS_MAIN = 0x02; /** * @notice Get user ID from the serialized order data * @param ser_data Serialized order data * @return userID User ID */ function _getOrderUserID(bytes memory ser_data) internal pure returns (uint256 userID) { userID = ser_data.toUint32(ORDER_SIZE - 4); } /** * @notice Get base token ID from the serialized order data * @param ser_data Serialized order data * @return tokenBase Base token ID */ function _getOrderTokenIDBase(bytes memory ser_data) internal pure returns (uint256 tokenBase) { tokenBase = ser_data.toUint16(ORDER_SIZE - 6); } /** * @notice Get base token amount from the serialized order data * @param ser_data Serialized order data * @return amountBase Base token amount */ function _getOrderAmountBase(bytes memory ser_data) internal pure returns (uint256 amountBase) { amountBase = ser_data.toUint(ORDER_SIZE - 38); } /** * @notice Get quote token ID from the serialized order data * @param ser_data Serialized order data * @return tokenQuote Quote token ID */ function _getOrderTokenIDQuote(bytes memory ser_data) internal pure returns (uint256 tokenQuote) { tokenQuote = ser_data.toUint16(ORDER_SIZE - 40); } /** * @notice Get quote token amount from the serialized order data * @param ser_data Serialized order data * @return amountQuote Quote token amount */ function _getOrderAmountQuote(bytes memory ser_data) internal pure returns (uint256 amountQuote) { amountQuote = ser_data.toUint(ORDER_SIZE - 72); } /** * @notice Check if the order is a buy order * @param ser_data Serialized order data * @return fBuy Is buy order or not */ function _isOrderBuy(bytes memory ser_data) internal pure returns (bool fBuy) { fBuy = (ser_data.toUint8(ORDER_SIZE - 73) & _MASK_IS_BUY != 0); } /** * @notice Check if the fee is paid by main token * @param ser_data Serialized order data * @return fMain Is the fee paid in main token or not */ function _isOrderFeeMain(bytes memory ser_data) internal pure returns (bool fMain) { fMain = (ser_data.toUint8(ORDER_SIZE - 73) & _MASK_IS_MAIN != 0); } /** * @notice Get nonce from the serialized order data * @param ser_data Serialized order data * @return nonce Nonce */ function _getOrderNonce(bytes memory ser_data) internal pure returns (uint256 nonce) { nonce = ser_data.toUint32(ORDER_SIZE - 77); } /** * @notice Get trading fee from the serialized order data * @param ser_data Serialized order data * @return fee Fee amount */ function _getOrderTradeFee(bytes memory ser_data) internal pure returns (uint256 tradeFee) { tradeFee = ser_data.toUint(ORDER_SIZE - 109); } /** * @notice Get gas fee from the serialized order data * @param ser_data Serialized order data * @return fee Fee amount */ function _getOrderGasFee(bytes memory ser_data) internal pure returns (uint256 gasFee) { gasFee = ser_data.toUint(ORDER_SIZE - 141); } /** * @notice Get v from the serialized order data * @param ser_data Serialized order data * @return v Signature v */ function _getOrderV(bytes memory ser_data) internal pure returns (uint8 v) { v = ser_data.toUint8(ORDER_SIZE - 142); } /** * @notice Get r from the serialized order data * @param ser_data Serialized order data * @return r Signature r */ function _getOrderR(bytes memory ser_data) internal pure returns (bytes32 r) { r = ser_data.toBytes32(ORDER_SIZE - 174); } /** * @notice Get s from the serialized order data * @param ser_data Serialized order data * @return s Signature s */ function _getOrderS(bytes memory ser_data) internal pure returns (bytes32 s) { s = ser_data.toBytes32(ORDER_SIZE - 206); } /** * @notice Get hash from the serialized order data * @param ser_data Serialized order data * @return hash Order hash without signature */ function _getOrderHash(bytes memory ser_data) internal pure returns (bytes32 hash) { hash = keccak256(ser_data.slice(65, UNSIGNED_ORDER_SIZE)); } /** * @notice Fetch the serialized order data with the given index * @param ser_data Serialized order data * @param index The index of order to be fetched * @return order_data The fetched order data */ function _getOrder(bytes memory ser_data, uint index) internal pure returns (bytes memory order_data) { require(index < _getOrderCount(ser_data)); order_data = ser_data.slice(ORDER_SIZE.mul(index), ORDER_SIZE); } /** * @notice Count the order amount * @param ser_data Serialized order data * @return amount Order amount */ function _getOrderCount(bytes memory ser_data) internal pure returns (uint256 amount) { amount = ser_data.length.div(ORDER_SIZE); } } /** * @title Serializable Withdrawal * @author Ben Huang * @notice Let withdrawal support serialization and deserialization */ contract SerializableWithdrawal { using SafeMath for uint256; using BytesLib for bytes; uint constant public WITHDRAWAL_SIZE = 140; uint constant public UNSIGNED_WITHDRAWAL_SIZE = 75; uint8 constant internal _MASK_IS_ETH = 0x01; /** * @notice Get user ID from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return userID User ID */ function _getWithdrawalUserID(bytes memory ser_data) internal pure returns (uint256 userID) { userID = ser_data.toUint32(WITHDRAWAL_SIZE - 4); } /** * @notice Get token ID from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return tokenID Withdrawal token ID */ function _getWithdrawalTokenID(bytes memory ser_data) internal pure returns (uint256 tokenID) { tokenID = ser_data.toUint16(WITHDRAWAL_SIZE - 6); } /** * @notice Get amount from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return amount Withdrawal token amount */ function _getWithdrawalAmount(bytes memory ser_data) internal pure returns (uint256 amount) { amount = ser_data.toUint(WITHDRAWAL_SIZE - 38); } /** * @notice Check if the fee is paid by main token * @param ser_data Serialized withdrawal data * @return fETH Is the fee paid in ETH or DGO */ function _isWithdrawalFeeETH(bytes memory ser_data) internal pure returns (bool fFeeETH) { fFeeETH = (ser_data.toUint8(WITHDRAWAL_SIZE - 39) & _MASK_IS_ETH != 0); } /** * @notice Get nonce from the serialized withrawal data * @param ser_data Serialized withdrawal data * @return nonce Nonce */ function _getWithdrawalNonce(bytes memory ser_data) internal pure returns (uint256 nonce) { nonce = ser_data.toUint32(WITHDRAWAL_SIZE - 43); } /** * @notice Get fee amount from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return fee Fee amount */ function _getWithdrawalFee(bytes memory ser_data) internal pure returns (uint256 fee) { fee = ser_data.toUint(WITHDRAWAL_SIZE - 75); } /** * @notice Get v from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return v Signature v */ function _getWithdrawalV(bytes memory ser_data) internal pure returns (uint8 v) { v = ser_data.toUint8(WITHDRAWAL_SIZE - 76); } /** * @notice Get r from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return r Signature r */ function _getWithdrawalR(bytes memory ser_data) internal pure returns (bytes32 r) { r = ser_data.toBytes32(WITHDRAWAL_SIZE - 108); } /** * @notice Get s from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return s Signature s */ function _getWithdrawalS(bytes memory ser_data) internal pure returns (bytes32 s) { s = ser_data.toBytes32(WITHDRAWAL_SIZE - 140); } /** * @notice Get hash from the serialized withdrawal data * @param ser_data Serialized withdrawal data * @return hash Withdrawal hash without signature */ function _getWithdrawalHash(bytes memory ser_data) internal pure returns (bytes32 hash) { hash = keccak256(ser_data.slice(65, UNSIGNED_WITHDRAWAL_SIZE)); } } /** * @title Dinngo * @author Ben Huang * @notice Main exchange contract for Dinngo */ contract Dinngo is SerializableOrder, SerializableWithdrawal, SerializableMigration { // Storage alignment address private _owner; mapping (address => bool) private admins; uint256 private _nAdmin; uint256 private _nLimit; // end using ECDSA for bytes32; using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public processTime; mapping (address => mapping (address => uint256)) public balances; mapping (bytes32 => uint256) public orderFills; mapping (uint256 => address payable) public userID_Address; mapping (uint256 => address) public tokenID_Address; mapping (address => uint256) public userRanks; mapping (address => uint256) public tokenRanks; mapping (address => uint256) public lockTimes; event AddUser(uint256 userID, address indexed user); event AddToken(uint256 tokenID, address indexed token); event Deposit(address token, address indexed user, uint256 amount, uint256 balance); event Withdraw( address token, address indexed user, uint256 amount, uint256 balance, address tokenFee, uint256 amountFee ); event Trade( address indexed user, bool isBuy, address indexed tokenBase, uint256 amountBase, address indexed tokenQuote, uint256 amountQuote, address tokenFee, uint256 amountFee ); event Lock(address indexed user, uint256 lockTime); event Unlock(address indexed user); /** * @dev All ether directly sent to contract will be refunded */ function() external payable { revert(); } /** * @notice Add the address to the user list. Event AddUser will be emitted * after execution. * @dev Record the user list to map the user address to a specific user ID, in * order to compact the data size when transferring user address information * @dev id should be less than 2**32 * @param id The user id to be assigned * @param user The user address to be added */ function addUser(uint256 id, address payable user) external { require(user != address(0)); require(userRanks[user] == 0); require(id < 2**32); if (userID_Address[id] == address(0)) userID_Address[id] = user; else require(userID_Address[id] == user); userRanks[user] = 1; emit AddUser(id, user); } /** * @notice Remove the address from the user list. * @dev The user rank is set to 0 to remove the user. * @param user The user address to be added */ function removeUser(address user) external { require(user != address(0)); require(userRanks[user] != 0); userRanks[user] = 0; } /** * @notice Update the rank of user. Can only be called by owner. * @param user The user address * @param rank The rank to be assigned */ function updateUserRank(address user, uint256 rank) external { require(user != address(0)); require(rank != 0); require(userRanks[user] != 0); require(userRanks[user] != rank); userRanks[user] = rank; } /** * @notice Add the token to the token list. Event AddToken will be emitted * after execution. * @dev Record the token list to map the token contract address to a specific * token ID, in order to compact the data size when transferring token contract * address information * @dev id should be less than 2**16 * @param id The token id to be assigned * @param token The token contract address to be added */ function addToken(uint256 id, address token) external { require(token != address(0)); require(tokenRanks[token] == 0); require(id < 2**16); if (tokenID_Address[id] == address(0)) tokenID_Address[id] = token; else require(tokenID_Address[id] == token); tokenRanks[token] = 1; emit AddToken(id, token); } /** * @notice Remove the token to the token list. * @dev The token rank is set to 0 to remove the token. * @param token The token contract address to be removed. */ function removeToken(address token) external { require(token != address(0)); require(tokenRanks[token] != 0); tokenRanks[token] = 0; } /** * @notice Update the rank of token. Can only be called by owner. * @param token The token contract address. * @param rank The rank to be assigned. */ function updateTokenRank(address token, uint256 rank) external { require(token != address(0)); require(rank != 0); require(tokenRanks[token] != 0); require(tokenRanks[token] != rank); tokenRanks[token] = rank; } /** * @notice The deposit function for ether. The ether that is sent with the function * call will be deposited. The first time user will be added to the user list. * Event Deposit will be emitted after execution. */ function deposit() external payable { require(!_isLocking(msg.sender)); require(msg.value > 0); balances[address(0)][msg.sender] = balances[address(0)][msg.sender].add(msg.value); emit Deposit(address(0), msg.sender, msg.value, balances[address(0)][msg.sender]); } /** * @notice The deposit function for tokens. The first time user will be added to * the user list. Event Deposit will be emitted after execution. * @param token Address of the token contract to be deposited * @param amount Amount of the token to be depositied */ function depositToken(address token, uint256 amount) external { require(token != address(0)); require(!_isLocking(msg.sender)); require(_isValidToken(token)); require(amount > 0); balances[token][msg.sender] = balances[token][msg.sender].add(amount); emit Deposit(token, msg.sender, amount, balances[token][msg.sender]); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); } /** * @notice The withdraw function for ether. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param amount The amount to be withdrawn. */ function withdraw(uint256 amount) external { require(_isLocked(msg.sender)); require(_isValidUser(msg.sender)); require(amount > 0); balances[address(0)][msg.sender] = balances[address(0)][msg.sender].sub(amount); emit Withdraw(address(0), msg.sender, amount, balances[address(0)][msg.sender], address(0), 0); msg.sender.transfer(amount); } /** * @notice The withdraw function for tokens. Event Withdraw will be emitted * after execution. User needs to be locked before calling withdraw. * @param token The token contract address to be withdrawn. * @param amount The token amount to be withdrawn. */ function withdrawToken(address token, uint256 amount) external { require(token != address(0)); require(_isLocked(msg.sender)); require(_isValidUser(msg.sender)); require(_isValidToken(token)); require(amount > 0); balances[token][msg.sender] = balances[token][msg.sender].sub(amount); emit Withdraw(token, msg.sender, amount, balances[token][msg.sender], address(0), 0); IERC20(token).safeTransfer(msg.sender, amount); } /** * @notice The withdraw function that can only be triggered by owner. * Event Withdraw will be emitted after execution. * @param withdrawal The serialized withdrawal data */ function withdrawByAdmin(bytes calldata withdrawal) external { address payable user = userID_Address[_getWithdrawalUserID(withdrawal)]; address wallet = userID_Address[0]; address token = tokenID_Address[_getWithdrawalTokenID(withdrawal)]; uint256 amount = _getWithdrawalAmount(withdrawal); uint256 amountFee = _getWithdrawalFee(withdrawal); address tokenFee = _isWithdrawalFeeETH(withdrawal)? address(0) : tokenID_Address[1]; uint256 balance = balances[token][user].sub(amount); require(_isValidUser(user)); _verifySig( user, _getWithdrawalHash(withdrawal), _getWithdrawalR(withdrawal), _getWithdrawalS(withdrawal), _getWithdrawalV(withdrawal) ); if (tokenFee == token) { balance = balance.sub(amountFee); } else { balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee); } balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee); balances[token][user] = balance; emit Withdraw(token, user, amount, balance, tokenFee, amountFee); if (token == address(0)) { user.transfer(amount); } else { IERC20(token).safeTransfer(user, amount); } } /** * @notice The migrate function the can only triggered by admin. * Event Migrate will be emitted after execution. * @param migration The serialized migration data */ function migrateByAdmin(bytes calldata migration) external { address target = _getMigrationTarget(migration); address user = userID_Address[_getMigrationUserID(migration)]; uint256 nToken = _getMigrationCount(migration); require(_isValidUser(user)); _verifySig( user, _getMigrationHash(migration), _getMigrationR(migration), _getMigrationS(migration), _getMigrationV(migration) ); for (uint i = 0; i < nToken; i++) { address token = tokenID_Address[_getMigrationTokenID(migration, i)]; uint256 balance = balances[token][user]; require(balance != 0); balances[token][user] = 0; if (token == address(0)) { Migratable(target).migrateTo.value(balance)(user, token, balance); } else { IERC20(token).approve(target, balance); Migratable(target).migrateTo(user, token, balance); } } } /** * @notice The settle function for orders. First order is taker order and the followings * are maker orders. * @param orders The serialized orders. */ function settle(bytes calldata orders) external { // Deal with the order list uint256 nOrder = _getOrderCount(orders); // Get the first order as the taker order bytes memory takerOrder = _getOrder(orders, 0); uint256 totalAmountBase = _getOrderAmountBase(takerOrder); uint256 takerAmountBase = totalAmountBase.sub(orderFills[_getOrderHash(takerOrder)]); uint256 fillAmountQuote = 0; uint256 restAmountBase = takerAmountBase; bool fBuy = _isOrderBuy(takerOrder); // Parse maker orders for (uint i = 1; i < nOrder; i++) { // Get ith order as the maker order bytes memory makerOrder = _getOrder(orders, i); require(fBuy != _isOrderBuy(makerOrder)); uint256 makerAmountBase = _getOrderAmountBase(makerOrder); // Calculate the amount to be executed uint256 amountBase = makerAmountBase.sub(orderFills[_getOrderHash(makerOrder)]); amountBase = amountBase <= restAmountBase? amountBase : restAmountBase; uint256 amountQuote = _getOrderAmountQuote(makerOrder).mul(amountBase).div(makerAmountBase); restAmountBase = restAmountBase.sub(amountBase); fillAmountQuote = fillAmountQuote.add(amountQuote); // Trade amountBase and amountQuote for maker order _trade(amountBase, amountQuote, makerOrder); } // Sum the trade amount and check takerAmountBase = takerAmountBase.sub(restAmountBase); if (fBuy) { require(fillAmountQuote.mul(totalAmountBase) <= _getOrderAmountQuote(takerOrder).mul(takerAmountBase)); } else { require(fillAmountQuote.mul(totalAmountBase) >= _getOrderAmountQuote(takerOrder).mul(takerAmountBase)); } // Trade amountBase and amountQuote for taker order _trade(takerAmountBase, fillAmountQuote, takerOrder); } /** * @notice Announce lock of the sender */ function lock() external { require(!_isLocking(msg.sender)); lockTimes[msg.sender] = now.add(processTime); emit Lock(msg.sender, lockTimes[msg.sender]); } /** * @notice Unlock the sender */ function unlock() external { require(_isLocking(msg.sender)); lockTimes[msg.sender] = 0; emit Unlock(msg.sender); } /** * @notice Change the processing time of locking the user address */ function changeProcessTime(uint256 time) external { require(processTime != time); processTime = time; } /** * @notice Process the trade by the providing information * @param amountBase The provided amount to be traded * @param amountQuote The amount to be requested * @param order The order that triggered the trading */ function _trade(uint256 amountBase, uint256 amountQuote, bytes memory order) internal { require(amountBase != 0); // Get parameters address user = userID_Address[_getOrderUserID(order)]; address wallet = userID_Address[0]; bytes32 hash = _getOrderHash(order); address tokenQuote = tokenID_Address[_getOrderTokenIDQuote(order)]; address tokenBase = tokenID_Address[_getOrderTokenIDBase(order)]; address tokenFee; uint256 amountFee = _getOrderTradeFee(order).mul(amountBase).div(_getOrderAmountBase(order)); require(_isValidUser(user)); // Trade and fee setting if (orderFills[hash] == 0) { _verifySig(user, hash, _getOrderR(order), _getOrderS(order), _getOrderV(order)); amountFee = amountFee.add(_getOrderGasFee(order)); } bool fBuy = _isOrderBuy(order); if (fBuy) { balances[tokenQuote][user] = balances[tokenQuote][user].sub(amountQuote); if (_isOrderFeeMain(order)) { tokenFee = tokenBase; balances[tokenBase][user] = balances[tokenBase][user].add(amountBase).sub(amountFee); balances[tokenBase][wallet] = balances[tokenBase][wallet].add(amountFee); } else { tokenFee = tokenID_Address[1]; balances[tokenBase][user] = balances[tokenBase][user].add(amountBase); balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee); balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee); } } else { balances[tokenBase][user] = balances[tokenBase][user].sub(amountBase); if (_isOrderFeeMain(order)) { tokenFee = tokenQuote; balances[tokenQuote][user] = balances[tokenQuote][user].add(amountQuote).sub(amountFee); balances[tokenQuote][wallet] = balances[tokenQuote][wallet].add(amountFee); } else { tokenFee = tokenID_Address[1]; balances[tokenQuote][user] = balances[tokenQuote][user].add(amountQuote); balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee); balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee); } } // Order fill orderFills[hash] = orderFills[hash].add(amountBase); emit Trade ( user, fBuy, tokenBase, amountBase, tokenQuote, amountQuote, tokenFee, amountFee ); } /** * @dev Check if the user is valid * @param user The user address to be checked. */ function _isValidUser(address user) internal view returns (bool) { return userRanks[user] != 0; } /** * @dev Check if the token is valid * @param token The token address to be checked. */ function _isValidToken(address token) internal view returns (bool) { return tokenRanks[token] != 0; } /** * @notice Verify if the data is signed by the given user and signature * @param user The signing user * @param hash The data hash to be verified * @param r The signature R * @param s The signature S * @param v The signature V */ function _verifySig(address user, bytes32 hash, bytes32 r, bytes32 s, uint8 v) internal pure { // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); address sigAddr = ecrecover(hash.toEthSignedMessageHash(), v, r, s); require(user == sigAddr); } /** * @notice Return if the give user has announced lock * @param user The user address to be queried * @return Query result */ function _isLocking(address user) internal view returns (bool) { return lockTimes[user] > 0; } /** * @notice Return if the user is locked * @param user The user address to be queried */ function _isLocked(address user) internal view returns (bool) { return _isLocking(user) && lockTimes[user] < now; } }
Get v from the serialized migration data ser_data Serialized migration data return v Signature v/
function _getMigrationV(bytes memory ser_data) internal pure returns (uint8 v) { v = ser_data.toUint8(SIGNATURE_SIZE - 1); }
15,834,804
./full_match/5/0x08f120f4Abf608e2c151B6513444449C8Cb6aF11/sources/contracts/AvaxGods.sol
Creates a new battle _name battle name; set by player
function createBattle(string memory _name) external returns (Battle memory) { bytes32 battleHash = keccak256(abi.encode(_name)); Battle memory _battle = Battle( ); uint256 _id = battles.length; battleInfo[_name] = _id; battles.push(_battle); return _battle; }
1,866,293
// SPDX-License-Identifier: MIT pragma solidity ^0.5.16; interface ComptrollerInterface { /** * @notice Marker function used for light validation when updating the comptroller of a market * @dev Implementations should simply return true. * @return true */ function isComptroller() external view returns (bool); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, ZUNUSED } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } /** * @title Exponential module for storing fixed-decision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); // XXX docs/verify event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); } /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "re-entered"); } } /** * @title The Compound InterestRateModel Interface * @author Compound * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ interface InterestRateModel { /** * @notice Gets the current borrow interest rate based on the given asset, total cash, total borrows * and total reserves. * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param cash The total cash of the underlying asset in the CToken * @param borrows The total borrows of the underlying asset in the CToken * @param reserves The total reserves of the underlying asset in the CToken * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Marker function used for light validation when updating the interest rate model of a market * @dev Marker function used for light validation when updating the interest rate model of a market. Implementations should simply return true. * @return Success or failure */ function isInterestRateModel() external view returns (bool); } /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is EIP20Interface, Exponential, TokenErrorReporter, ReentrancyGuard { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint256 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 constant borrowRateMaxMantissa = 5e14; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 public initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of total earned interest since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) accountBorrows; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest( uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows ); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow( address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller( ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller ); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel( InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel ); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor( uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa ); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced( address admin, uint256 reduceAmount, uint256 newTotalReserves ); /** * @notice Construct a new money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ constructor( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint256 decimals_ ) internal { // Set admin to msg.sender admin = msg.sender; // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require( initialExchangeRateMantissa > 0, "Initial exchange rate must be greater than zero." ); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "Setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require( err == uint256(Error.NO_ERROR), "Setting interest rate model failed" ); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { /* Fail if transfer not allowed */ uint256 allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed ); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint256 allowanceNew; uint256 srcTokensNew; uint256 dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); /* We call the defense hook (which checks for under-collateralization) */ comptroller.transferVerify(address(this), src, dst, tokens); return uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint256 balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = accountTokens[account]; uint256 borrowBalance; uint256 exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint256(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint256(Error.MATH_ERROR), 0, 0, 0); } return ( uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa ); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { (uint256 opaqueErr, uint256 borrowRateMantissa) = interestRateModel.getBorrowRate( getCashPrior(), totalBorrows, totalReserves ); require( opaqueErr == 0, "borrowRatePerBlock: interestRateModel.borrowRate failed" ); // semi-opaque return borrowRateMantissa; } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { /* We calculate the supply rate: * underlying = totalSupply × exchangeRate * borrowsPer = totalBorrows ÷ underlying * supplyRate = borrowRate × (1-reserveFactor) × borrowsPer */ uint256 exchangeRateMantissa = exchangeRateStored(); (uint256 e0, uint256 borrowRateMantissa) = interestRateModel.getBorrowRate( getCashPrior(), totalBorrows, totalReserves ); require(e0 == 0, "supplyRatePerBlock: calculating borrowRate failed"); // semi-opaque (MathError e1, Exp memory underlying) = mulScalar(Exp({mantissa: exchangeRateMantissa}), totalSupply); require( e1 == MathError.NO_ERROR, "supplyRatePerBlock: calculating underlying failed" ); (MathError e2, Exp memory borrowsPer) = divScalarByExp(totalBorrows, underlying); require( e2 == MathError.NO_ERROR, "supplyRatePerBlock: calculating borrowsPer failed" ); (MathError e3, Exp memory oneMinusReserveFactor) = subExp( Exp({mantissa: mantissaOne}), Exp({mantissa: reserveFactorMantissa}) ); require( e3 == MathError.NO_ERROR, "supplyRatePerBlock: calculating oneMinusReserveFactor failed" ); (MathError e4, Exp memory supplyRate) = mulExp3( Exp({mantissa: borrowRateMantissa}), oneMinusReserveFactor, borrowsPer ); require( e4 == MathError.NO_ERROR, "supplyRatePerBlock: calculating supplyRate failed" ); return supplyRate.mantissa; } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { require( accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed" ); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { require( accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed" ); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { (MathError err, uint256 result) = borrowBalanceStoredInternal(account); require( err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed" ); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint256) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint256 principalTimesIndex; uint256 result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt( borrowSnapshot.principal, borrowIndex ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt( principalTimesIndex, borrowSnapshot.interestIndex ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { require( accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed" ); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { (MathError err, uint256 result) = exchangeRateStoredInternal(); require( err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed" ); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint256) { if (totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt( totalCash, totalBorrows, totalReserves ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp( cashPlusBorrowsMinusReserves, totalSupply ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } struct AccrueInterestLocalVars { MathError mathErr; uint256 opaqueErr; uint256 borrowRateMantissa; uint256 currentBlockNumber; uint256 blockDelta; Exp simpleInterestFactor; uint256 interestAccumulated; uint256 totalBorrowsNew; uint256 totalReservesNew; uint256 borrowIndexNew; } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { AccrueInterestLocalVars memory vars; /* Calculate the current borrow interest rate */ (vars.opaqueErr, vars.borrowRateMantissa) = interestRateModel .getBorrowRate(getCashPrior(), totalBorrows, totalReserves); require( vars.borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high" ); if (vars.opaqueErr != 0) { return failOpaque( Error.INTEREST_RATE_MODEL_ERROR, FailureInfo.ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, vars.opaqueErr ); } /* Remember the initial block number */ vars.currentBlockNumber = getBlockNumber(); /* Calculate the number of blocks elapsed since the last accrual */ (vars.mathErr, vars.blockDelta) = subUInt( vars.currentBlockNumber, accrualBlockNumber ); assert(vars.mathErr == MathError.NO_ERROR); // Block delta should always succeed and if it doesn't, blow up. /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ (vars.mathErr, vars.simpleInterestFactor) = mulScalar( Exp({mantissa: vars.borrowRateMantissa}), vars.blockDelta ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.interestAccumulated) = mulScalarTruncate( vars.simpleInterestFactor, totalBorrows ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalBorrowsNew) = addUInt( vars.interestAccumulated, totalBorrows ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalReservesNew) = mulScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), vars.interestAccumulated, totalReserves ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.borrowIndexNew) = mulScalarTruncateAddUInt( vars.simpleInterestFactor, borrowIndex, borrowIndex ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint256(vars.mathErr) ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = vars.currentBlockNumber; borrowIndex = vars.borrowIndexNew; totalBorrows = vars.totalBorrowsNew; totalReserves = vars.totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest( vars.interestAccumulated, vars.borrowIndexNew, totalBorrows ); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mintInternal(uint256 mintAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 mintTokens; uint256 totalSupplyNew; uint256 accountTokensNew; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mintFresh(address minter, uint256 mintAmount) internal returns (uint256) { /* Fail if mint not allowed */ uint256 allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK); } MintLocalVars memory vars; /* Fail if checkTransferIn fails */ vars.err = checkTransferIn(minter, mintAmount); if (vars.err != Error.NO_ERROR) { return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_NOT_POSSIBLE); } /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = mintAmount / exchangeRate */ ( vars.mathErr, vars.exchangeRateMantissa ) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate( mintAmount, Exp({mantissa: vars.exchangeRateMantissa}) ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_CALCULATION_FAILED, uint256(vars.mathErr) ); } /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt( totalSupply, vars.mintTokens ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.accountTokensNew) = addUInt( accountTokens[minter], vars.mintTokens ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the minter and the mintAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional mintAmount of cash. * If doTransferIn fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferIn(minter, mintAmount); if (vars.err != Error.NO_ERROR) { return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_FAILED); } /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, mintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify( address(this), minter, mintAmount, vars.mintTokens ); return uint256(Error.NO_ERROR); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 redeemTokens; uint256 redeemAmount; uint256 totalSupplyNew; uint256 accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be zero) * @param redeemAmountIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn ) internal returns (uint256) { require( redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero" ); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ ( vars.mathErr, vars.exchangeRateMantissa ) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr) ); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate( Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint256(vars.mathErr) ); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate( redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}) ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint256(vars.mathErr) ); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint256 allowed = comptroller.redeemAllowed( address(this), redeemer, vars.redeemTokens ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK ); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt( totalSupply, vars.redeemTokens ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.accountTokensNew) = subUInt( accountTokens[redeemer], vars.redeemTokens ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * If doTransferOut fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferOut(redeemer, vars.redeemAmount); require(vars.err == Error.NO_ERROR, "redeem transfer out failed"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify( address(this), redeemer, vars.redeemAmount, vars.redeemTokens ); return uint256(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { Error err; MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint256 borrowAmount) internal returns (uint256) { /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK ); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE ); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal( borrower ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.accountBorrowsNew) = addUInt( vars.accountBorrows, borrowAmount ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalBorrowsNew) = addUInt( totalBorrows, borrowAmount ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * If doTransferOut fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferOut(borrower, borrowAmount); require(vars.err == Error.NO_ERROR, "borrow transfer out failed"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow( borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew ); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowInternal(uint256 repayAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail( Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED ); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalfInternal(address borrower, uint256 repayAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail( Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED ); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount ) internal returns (uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed( address(this), payer, borrower, repayAmount ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK ); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal( borrower ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } /* Fail if checkTransferIn fails */ vars.err = checkTransferIn(payer, vars.repayAmount); if (vars.err != Error.NO_ERROR) { return fail( vars.err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - repayAmount * totalBorrowsNew = totalBorrows - repayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt( vars.accountBorrows, vars.repayAmount ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalBorrowsNew) = subUInt( totalBorrows, vars.repayAmount ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * If doTransferIn fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferIn(payer, vars.repayAmount); require(vars.err == Error.NO_ERROR, "repay borrow transfer in failed"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow( payer, borrower, vars.repayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew ); /* We call the defense hook */ comptroller.repayBorrowVerify( address(this), payer, borrower, vars.repayAmount, vars.borrowerIndex ); return uint256(Error.NO_ERROR); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CToken cTokenCollateral ) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail( Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED ); } error = cTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return fail( Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED ); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh( msg.sender, borrower, repayAmount, cTokenCollateral ); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CToken cTokenCollateral ) internal returns (uint256) { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK ); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK ); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail( Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER ); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO ); } /* Fail if repayAmount = -1 */ if (repayAmount == uint256(-1)) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX ); } /* We calculate the number of collateral tokens that will be seized */ (uint256 amountSeizeError, uint256 seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), repayAmount ); if (amountSeizeError != 0) { return failOpaque( Error.COMPTROLLER_CALCULATION_ERROR, FailureInfo .LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, amountSeizeError ); } /* Fail if seizeTokens > borrower collateral token balance */ if (seizeTokens > cTokenCollateral.balanceOf(borrower)) { return fail( Error.TOKEN_INSUFFICIENT_BALANCE, FailureInfo.LIQUIDATE_SEIZE_TOO_MUCH ); } /* Fail if repayBorrow fails */ uint256 repayBorrowError = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint256(Error.NO_ERROR)) { return fail( Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED ); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ uint256 seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow( liquidator, borrower, repayAmount, address(cTokenCollateral), seizeTokens ); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount, seizeTokens ); return uint256(Error.NO_ERROR); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { /* Fail if seize not allowed */ uint256 allowed = comptroller.seizeAllowed( address(this), msg.sender, liquidator, borrower, seizeTokens ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed ); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail( Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER ); } MathError mathErr; uint256 borrowerTokensNew; uint256 liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt( accountTokens[borrower], seizeTokens ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint256(mathErr) ); } (mathErr, liquidatorTokensNew) = addUInt( accountTokens[liquidator], seizeTokens ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(mathErr) ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify( address(this), msg.sender, liquidator, borrower, seizeTokens ); return uint256(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) * * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address? */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK ); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail( Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK ); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK ); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail( Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED ); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK ); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { // TODO: static_assert + no error code? return fail( Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK ); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail( Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK ); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor( oldReserveFactorMantissa, newReserveFactorMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail( Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED ); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { Error err; // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK ); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { // TODO: static_assert + no error code? return fail( Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK ); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE ); } // Check reduceAmount ≤ reserves[n] (totalReserves) // TODO: I'm following the spec literally here but I think we should we just use SafeMath instead and fail on an error (which would be underflow) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require( totalReservesNew <= totalReserves, "reduce reserves unexpected underflow" ); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // invoke doTransferOut(reduceAmount, admin) err = doTransferOut(admin, reduceAmount); // we revert on the failure of this command require(err == Error.NO_ERROR, "reduce reserves transfer out failed"); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail( Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED ); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK ); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { // TODO: static_assert + no error code? return fail( Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK ); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require( newInterestRateModel.isInterestRateModel(), "marker method returned false" ); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel( oldInterestRateModel, newInterestRateModel ); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address from, uint256 amount) internal view returns (Error); /** * @dev Performs a transfer in, ideally returning an explanatory error code upon failure rather than reverting. * If caller has not called `checkTransferIn`, this may revert due to insufficient balance or insufficient allowance. * If caller has called `checkTransferIn` successfully, this should not revert in normal conditions. */ function doTransferIn(address from, uint256 amount) internal returns (Error); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint256 amount) internal returns (Error); } /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ constructor( address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint256 decimals_ ) public CToken( comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_ ) { // Set underlying underlying = underlying_; EIP20Interface(underlying).totalSupply(); // Sanity check the underlying } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint256 mintAmount) external returns (uint256) { return mintInternal(mintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 repayAmount) external returns (uint256) { return repayBorrowInternal(repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) { return repayBorrowBehalfInternal(borrower, repayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint256 repayAmount, CToken cTokenCollateral ) external returns (uint256) { return liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint256) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address from, uint256 amount) internal view returns (Error) { EIP20Interface token = EIP20Interface(underlying); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint256 amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); bool result; token.transferFrom(from, address(this), amount); // solium-disable-next-line security/no-inline-assembly assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_IN_FAILED; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint256 amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); bool result; token.transfer(to, amount); // solium-disable-next-line security/no-inline-assembly assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } }
Applies accrued interest to total borrows and reserves. This calculates interest accrued from the last checkpointed block up to the current block and writes new checkpoint to storage./ Calculate the current borrow interest rate /
function accrueInterest() public returns (uint256) { AccrueInterestLocalVars memory vars; (vars.opaqueErr, vars.borrowRateMantissa) = interestRateModel .getBorrowRate(getCashPrior(), totalBorrows, totalReserves); require( vars.borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high" ); if (vars.opaqueErr != 0) { return failOpaque( Error.INTEREST_RATE_MODEL_ERROR, FailureInfo.ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, vars.opaqueErr ); } vars.currentBlockNumber, accrualBlockNumber ); vars.blockDelta ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.interestAccumulated) = mulScalarTruncate( vars.simpleInterestFactor, totalBorrows ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalBorrowsNew) = addUInt( vars.interestAccumulated, totalBorrows ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalReservesNew) = mulScalarTruncateAddUInt( vars.interestAccumulated, totalReserves ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.borrowIndexNew) = mulScalarTruncateAddUInt( vars.simpleInterestFactor, borrowIndex, borrowIndex ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint256(vars.mathErr) ); } borrowIndex = vars.borrowIndexNew; totalBorrows = vars.totalBorrowsNew; totalReserves = vars.totalReservesNew; vars.interestAccumulated, vars.borrowIndexNew, totalBorrows ); return uint256(Error.NO_ERROR); }
1,819,483
// SPDX-License-Identifier: MIT /** This example code is designed to quickly deploy an example contract using Remix. * If you have never used Remix, try our example walkthrough: https://docs.chain.link/docs/example-walkthrough * You will need testnet ETH and LINK. * - Kovan ETH faucet: https://faucet.kovan.network/ * - Kovan LINK faucet: https://kovan.chain.link/ */ pragma solidity >=0.6.6; import "./VRFConsumerBase.sol"; import "./IRandom.sol"; import "./Ownable.sol"; contract RandomNumberConsumer is VRFConsumerBase, IRandom, Ownable { bytes32 internal keyHash; uint256 internal fee; uint8 public randomIterations; uint256 public randomResult; mapping(bytes32 => uint256) public rand; mapping(address => bool) private allowedAddrs; bytes32 public latestRequest; event Request(bytes32 requestId, address user, uint256 poolId, uint256 globalAssetId); event Response(bytes32 requestId); modifier onlyAllowedAddrs() { require(allowedAddrs[msg.sender], "Address: should be allowed"); _; } /** * Constructor inherits VRFConsumerBase * * Network: Kovan * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9 * LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088 * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4 */ constructor(uint8 _random) VRFConsumerBase( 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, // VRF Coordinator polygon 0x326C977E6efc84E512bB9C30f76E30c160eD06FB // LINK Token polygon ) public { keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4; fee = 0.0001 * 10 ** 18; // 0.1 LINK randomIterations = _random; } /** * Requests randomness */ function getRandomNumber(address user, uint256 poolId, uint256 globalAssetId) public override onlyAllowedAddrs returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) > fee, "Not enough LINK - fill contract with faucet"); latestRequest = requestRandomness(keyHash, fee); emit Request(latestRequest, user, poolId, globalAssetId); return latestRequest; } function _expand(uint256 randomValue, uint8 randomAmount) internal pure returns (uint256[] memory expandedValues) { expandedValues = new uint256[](randomAmount); for (uint256 i = 0; i < randomAmount; i++) { expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i))); } return expandedValues; } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { rand[requestId] = randomness; emit Response (requestId); } function setIterations(uint8 iter) public onlyOwner { randomIterations = iter; } function expandByRequest(bytes32 requestId, uint8 randomAmount) public view returns(uint256[] memory) { return _expand(rand[requestId],randomAmount); } /** * Withdraw LINK from this contract * * DO NOT USE THIS IN PRODUCTION AS IT CAN BE CALLED BY ANY ADDRESS. * THIS IS PURELY FOR EXAMPLE PURPOSES. */ function withdrawLink() external onlyOwner { require(LINK.transfer(msg.sender, LINK.balanceOf(address(this))), "Unable to transfer"); } function addAllowedAddr(address _contract) public override onlyOwner returns (bool) { allowedAddrs[_contract] = true; return true; } function removeAllowedAddr(address _contract) public override onlyOwner returns (bool) { allowedAddrs[_contract] = false; return true; } }
Callback function used by VRF Coordinator/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { rand[requestId] = randomness; emit Response (requestId); }
14,068,983
pragma solidity ^0.5.5; import '@openzeppelin/contracts/lifecycle/Pausable.sol'; import '@openzeppelin/contracts/ownership/Ownable.sol'; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../library/SafeERC20.sol"; import "../interface/IERC20.sol"; /// @title NoCashOpenSale Contract contract NoCashOpenSale is Pausable,Ownable { using SafeMath for uint256; using Address for address; struct condition { uint256 price; //_noCash per eth uint256 limitFund; //a quota uint256 startTime; //the stage start time uint256 maxSoldAmount; //the stage max sold amount } // uint8 public constant _whiteListStage1 = 1; uint8 public constant _whiteListStage5 = 5; // /// All deposited ETH will be instantly forwarded to this address. address payable public _teamWallet = 0x6666666666666666666666666666666666666666; /// IERC20 compilant _nocash token contact instance IERC20 public _nocash = IERC20(0x6666666666666666666666666666666666666666); /// tags show address can join in open sale mapping (uint8 => mapping (address => bool)) public _fullWhiteList; //the stage condition map mapping (uint8 => condition) public _stageCondition; //the user get fund per stage mapping (uint8 => mapping (address => uint256) ) public _stageFund; //the stage had sold amount mapping (uint8 => uint256) public _stageSoldAmount; /* * EVENTS */ event eveNewSale(address indexed destAddress, uint256 ethCost, uint256 gotTokens); event eveClaim(address indexed destAddress, uint256 gotTokens); event eveTeamWallet(address wallet); /// @dev valid the address modifier validAddress( address addr ) { require(addr != address(0x0)); require(addr != address(this)); _; } constructor() public { pause(); // uint256 testRate = 100; // uint256 testRate2 = 1000; // setCondition(1,3500 * testRate2,10*1e18/testRate, now, 525000*1e18); // setCondition(2,2500 * testRate2,5 *1e18/testRate, now + 1 days, 375000*1e18); // setCondition(3,2000 * testRate2,5 *1e18/testRate, now + 1 days, 600000*1e18); // setCondition(4,1500 * testRate2,5 *1e18/testRate, now + 1 days, 450000*1e18); // setCondition(5,1500 * testRate2,2 *1e18/testRate, now + 3 days, 150000*1e18); setCondition(1,3500 ,10*1e18, now, 525000*1e18); setCondition(2,2500 ,5 *1e18, now + 1 days, 375000*1e18); setCondition(3,2000 ,5 *1e18, now + 1 days, 600000*1e18); setCondition(4,1500 ,5 *1e18, now + 1 days, 450000*1e18); setCondition(5,1500 ,2 *1e18, now + 3 days, 150000*1e18); } /** * @dev for set team wallet */ function setTeamWallet(address payable wallet) public onlyOwner { require(wallet != address(0x0)); _teamWallet = wallet; emit eveTeamWallet(wallet); } /// @dev set the sale condition for every stage; function setCondition( uint8 stage, uint256 price, uint256 limitFund, uint256 startTime, uint256 maxSoldAmount ) internal onlyOwner { _stageCondition[stage].price = price; _stageCondition[stage].limitFund =limitFund; _stageCondition[stage].startTime= startTime; _stageCondition[stage].maxSoldAmount=maxSoldAmount; } /// @dev set the sale start time for every stage; function setStartTime(uint8 stage,uint256 startTime ) public onlyOwner { _stageCondition[stage].startTime = startTime; } /// @dev batch set quota for user admin /// if openTag <=0, removed function setWhiteList(uint8 stage, address[] calldata users, bool openTag) external onlyOwner { for (uint256 i = 0; i < users.length; i++) { _fullWhiteList[stage][users[i]] = openTag; } } /// @dev batch set quota for early user quota /// if openTag <=0, removed function addWhiteList(uint8 stage, address user, bool openTag) external onlyOwner { _fullWhiteList[stage][user] = openTag; } /** * @dev If anybody sends Ether directly to this contract, consider he is getting NoCash token */ function () external payable { buyNoCash(msg.sender); } // function getStage( ) view public returns(uint8) { for(uint8 i=1; i<6; i++){ uint256 startTime = _stageCondition[i].startTime; if(now >= startTime && _stageSoldAmount[i] < _stageCondition[i].maxSoldAmount ){ return i; } } return 0; } // function conditionCheck( address addr ) view internal returns(uint8) { uint8 stage = getStage(); require(stage!=0,"stage not begin"); uint256 fund = _stageFund[stage][addr]; require(fund < _stageCondition[stage].limitFund,"stage fund is full "); return stage; } /// @dev Exchange msg.value ether to NoCash for account recepient /// @param receipient NoCash tokens receiver function buyNoCash(address receipient) internal whenNotPaused validAddress(receipient) returns (bool) { // Do not allow contracts to game the system require(tx.gasprice <= 500000000000 wei); uint8 stage = conditionCheck(receipient); if(stage==_whiteListStage1 || stage==_whiteListStage5 ){ require(_fullWhiteList[stage][receipient],"your are not in the whitelist "); } doBuy(receipient, stage); return true; } /// @dev Buy NoCash token normally function doBuy(address receipient, uint8 stage) internal { // protect partner quota in stage one uint256 value = msg.value; uint256 fund = _stageFund[stage][receipient]; fund = fund.add(value); if (fund > _stageCondition[stage].limitFund ) { uint256 refund = fund.sub(_stageCondition[stage].limitFund); value = value.sub(refund); msg.sender.transfer(refund); } uint256 soldAmount = _stageSoldAmount[stage]; uint256 tokenAvailable = _stageCondition[stage].maxSoldAmount.sub(soldAmount); require(tokenAvailable > 0); uint256 costValue = 0; uint256 getTokens = 0; // all conditions has checked in the caller functions uint256 price = _stageCondition[stage].price; getTokens = price * value; if (tokenAvailable >= getTokens) { costValue = value; } else { costValue = tokenAvailable.div(price); getTokens = tokenAvailable; } if (costValue > 0) { _stageSoldAmount[stage] = _stageSoldAmount[stage].add(getTokens); _stageFund[stage][receipient]=_stageFund[stage][receipient].add(costValue); _nocash.mint(msg.sender, getTokens); emit eveNewSale(receipient, costValue, getTokens); } // not enough token sale, just return eth uint256 toReturn = value.sub(costValue); if (toReturn > 0) { msg.sender.transfer(toReturn); } } // get sale eth function seizeEth() external { uint256 _currentBalance = address(this).balance; _teamWallet.transfer(_currentBalance); } }
set the sale start time for every stage;
function setStartTime(uint8 stage,uint256 startTime ) public onlyOwner { _stageCondition[stage].startTime = startTime; }
5,356,732
./partial_match/1/0x2fC947e908Bc9a0A1E3098a34115765376d0b87f/sources/GamblxJackpot.sol
Get total ticket for game/
function getGameTotalTickets(uint playedGame) public view returns(uint) { return tickets[playedGame]; }
2,670,025
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./interfaces/IStakedToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract AaveRestaker is ERC20 { using SafeERC20 for IERC20; using SafeERC20 for IStakedToken; using SafeMath for uint256; address public manager; //Strategist address (where the fees go) IStakedToken stkAave; //stkAAVE interface IERC20 aave; //AAVE interface uint256 public totalStkAave; //Total pool stkAAVE uint256 public poolRewards; //Total pool rewards to claim uint256 public totalShares; //Total pool shares uint256 public fee; //Current fee in bps (1 = 0.01%) (Charged on compounding ONLY) /* REMOVED MAX FEE, REASON: There is no need for a fee cap, the fee is public and only charged upon compounding. Thus, no losses can occur for holders. Should the manager become a DAO, it is encouraged that fees be thoroughly calculated to maintain profitability over simply non-compounding stkAAVE. uint256 public maxFee; //Max fee in bps */ //Initialize variables and approve stkAave constructor(address stkAaveAddress, address aaveAddress, uint256 _fee, address _manager) ERC20("Pool-Staked AAVE", "pStkAAVE") public { stkAave = IStakedToken(stkAaveAddress); aave = IERC20(aaveAddress); totalShares = 0; totalStkAave = 0; poolRewards = 0; uint256 maxInt = uint256(-1); fee = _fee; manager = _manager; aave.safeApprove(address(stkAave), maxInt); } event Deposit( address indexed _from, uint256 _value ); event ClaimAndStake( uint256 _value, uint256 _fee ); event Withdraw( address indexed _from, uint256 _shares ); event FeeChanged( uint256 _newFee ); modifier onlyManager { require(msg.sender == manager, "Only the manager can call this function."); _; } //Updates pool balances function updateStkAaveAndShares() internal { totalStkAave = stkAave.balanceOf(address(this)); totalShares = totalSupply(); } //Deposit function (1e18 shares begins as 1 AAVE) //First, fetch the pool's total staked AAVE //Then transfer in the caller's AAVE and stake it function deposit(uint256 amount) external { updateStkAaveAndShares(); aave.safeTransferFrom(msg.sender, address(this), amount); stkAave.stake(address(this), amount); //Initialize the user's shares to mint and calculate the appropriate amount uint256 sharesToMint = 0; if (totalStkAave > 0 && totalShares > 0) { sharesToMint = amount.mul(totalShares).div(totalStkAave); } else if (totalStkAave == 0 && totalShares == 0) { sharesToMint = amount; } require(sharesToMint > 0, "No shares to mint."); //Assign shares to depositor and update state variables _mint(msg.sender, sharesToMint); updateStkAaveAndShares(); emit Deposit(msg.sender, amount); } //Check total pool pending AAVE rewards function checkRewards() external view returns (uint256) { return stkAave.getTotalRewardsBalance(address(this)); } //Claims and re-invests AAVE rewards, then update the pool's total stkAAVE function claimAndStake() external onlyManager { stkAave.claimRewards(address(this), uint(-1)); uint256 aaveBalance = aave.balanceOf(address(this)); require(aaveBalance > 0, "Cannot stake 0 tokens."); //Calculate fee uint256 aaveFee = aaveBalance.mul(fee).div(10000); //Transfer AAVE fee aave.safeTransfer(manager, aaveFee); //Stake AAVE stkAave.stake(address(this), aaveBalance); updateStkAaveAndShares(); emit ClaimAndStake(aaveBalance, aaveFee); } //Withdraws a set amount of shares to transfer stkAAVE back to the user //First, fetch the user's shares //Next, calculate the amount of stkAAVE to transfer to the user //Lastly, transfer them back. Can't use safeTransfer, so manually checking success function withdrawShares(uint256 shareCount) external { updateStkAaveAndShares(); //Security uint256 userShareCount = balanceOf(msg.sender); require(userShareCount > 0, "No pool ownership."); shareCount = shareCount > userShareCount ? userShareCount : shareCount; uint256 stkAaveToWithdraw = shareCount.mul(totalStkAave).div(totalShares); _burn(msg.sender, shareCount); stkAave.safeTransfer(msg.sender, stkAaveToWithdraw); updateStkAaveAndShares(); emit Withdraw(msg.sender, shareCount); } //Returns the user's stkAAVE balance in the pool function stkAaveBalanceOf(address query) external view returns (uint256) { require(balanceOf(query) > 0, "Queried address has no shares."); uint256 userStkAaveBalance = balanceOf(query).mul(totalStkAave).div(totalShares); return userStkAaveBalance; } function transferManager(address target) external onlyManager { manager = target; } function changeFeeBps(uint256 newFee) external onlyManager { fee = newFee; emit FeeChanged(newFee); } }
Updates pool balances
function updateStkAaveAndShares() internal { totalStkAave = stkAave.balanceOf(address(this)); totalShares = totalSupply(); }
12,725,219
./full_match/4/0x93AB3644E85Bc30fEb5FdeB6216a1745AC1B816F/sources/E/workspace/tony/dsy-protocol/contracts/Implementation.sol
price = price.mul(103);
function step() internal { Decimal.D256 memory price = oracleCapture(); if (price.greaterThan(Decimal.one())) { if (eraStatus() == Era.Status.CONTRACTION) updateEra(Era.Status.EXPANSION); growSupply(price); return; } if (price.lessThan(Decimal.one())) { if (eraStatus() == Era.Status.EXPANSION) updateEra(Era.Status.CONTRACTION); shrinkSupply(price); return; } emit SupplyNeutral(epoch()); }
784,017
./partial_match/42220/0x8913238836B742bA9635d23502F0359A687F8797/sources/src/SpiralsCeloVault.sol
Returns a GoldToken.sol interface for interacting with the smart contract.
function getGoldTokenV2() public view returns (address) { address goldTokenAddr = IRegistry(c_celoRegistry) .getAddressForStringOrDie("GoldToken"); return goldTokenAddr; }
3,497,371
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract NecoSaleContract is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; using Address for address; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _addressSet; mapping (address=>bool) public whitelist; address public devAddress; // NECO Token Price; 1 NECO for 3 busd uint public necoTokenPrice = 3; // NECO Token Amount in this contract. for 100 whitelists uint public necoTokenTotalAmount = 50000 * 1e18; bool public initialized = false; // the amount of slod neco. uint public necoTokenTotalSoldAmount = 0; // the accounts which bought neco. EnumerableSet.AddressSet private _accountBoughtNeco; // Max limitation for every account; 1500U for everyone uint public buyLimit = 1500 * 1e18; // Claim Map struct ClaimTimeStruct { uint startTime; uint endTime; } mapping (uint => ClaimTimeStruct) public claimTimes; // How much token user has bought. mapping (address => uint) public hasBoughtPerAccount; // How much token user can claim for per account. mapping (address => uint) public necoTokenAmountPerAccount; mapping (address => mapping (uint => uint)) public userClaimRoadMap; /** Contract Switch */ bool public saleStarted = false; bool public fcfsEnabled = false; bool public claimEnabled = false; IERC20 public necoToken; IERC20 public busd; event BuyNecoSuccess(address indexed account, uint usdAmount, uint necoAmount); event ClaimSuccess(address indexed account, uint necoAmount); // for that time, we may need to add whitelist 1 by 1, or we may init them at one time. constructor(IERC20 _necoToken, IERC20 _busd) { devAddress = owner(); necoToken = _necoToken; busd = _busd; initWhitelist(); } // add account into whitelist. function addToWhitelist(address account) external onlyOwner { require(_addressSet.length() <= 100, "out of limit"); require(whitelist[account] == false && account != address(0), "This account is already in whitelist."); whitelist[account] = true; _addressSet.add(account); } // remove account from whitelist. function removeFromWhitelist(address account) external onlyOwner { require(whitelist[account] && account != address(0), "This account is not in whitelist."); whitelist[account] = false; _addressSet.remove(account); } function setDevAddress(address account) external onlyOwner { require(account != address(this), "account can not be 0!"); devAddress = account; } // start sale function startSale() external onlyOwner { require(initialized, "Need to call initData firstly."); saleStarted = true; } function stopSale() external onlyOwner { saleStarted = false; } // this contract will be deployed on Polygon, So we should deposit NECO tokens // into this contract and setup its status. function initData() external onlyOwner { necoToken.transferFrom(msg.sender, address(this), necoTokenTotalAmount); initialized = true; } // enable claim. will be generate 9 time interval. // so we can get the index for claiming according to current time. function enableClaim() external onlyOwner { claimEnabled = true; uint claimPeriod = 30 days; uint claimStartTime = block.timestamp; uint claimEndTime = block.timestamp + claimPeriod; for (uint i = 0; i < 5; i ++) { claimTimes[i].startTime = claimStartTime; claimTimes[i].endTime = claimEndTime; claimStartTime = claimEndTime; claimEndTime = claimEndTime + claimPeriod; } } // get index of cliaming accroding to current time. function getCurrentIndexOfClaim() view public returns(uint) { uint currentTime = block.timestamp; for (uint i = 0; i < 5; i ++) { if (currentTime >= claimTimes[i].startTime && currentTime < claimTimes[i].endTime) { return i; } } return 5; } // set neco token again. function setNecoTokenPrice(uint newPrice) external onlyOwner { necoTokenPrice = newPrice; } // set buy limit again function setBuyLimit(uint newLimit) external onlyOwner { buyLimit = newLimit; } // open buying for everyone function changeToFCFS() external onlyOwner { fcfsEnabled = true; } // buy NECO token. function buyNecoToken(uint necoAmount) external saleHasStarted needHaveRemaining returns(bool) { if (!fcfsEnabled) { require(whitelist[msg.sender], "You are not in whitelist, you can wait for FCFS"); } require(necoAmount >= 1e18, "at least 1 NECO"); uint busdAmountRequired = necoAmount.mul(necoTokenPrice); require(hasBoughtPerAccount[msg.sender].add(busdAmountRequired) <= buyLimit, "Oh no! You want to buy too much"); require(necoAmount <= necoTokenTotalAmount, "Oh no! there is no enough token remaining."); busd.safeTransferFrom(msg.sender, devAddress, busdAmountRequired); // update status hasBoughtPerAccount[msg.sender] = hasBoughtPerAccount[msg.sender].add(busdAmountRequired); necoTokenAmountPerAccount[msg.sender] = necoTokenAmountPerAccount[msg.sender].add(necoAmount); buildClaimRoadmap(msg.sender); necoTokenTotalAmount = necoTokenTotalAmount.sub(necoAmount); necoTokenTotalSoldAmount = necoTokenTotalSoldAmount.add(necoAmount); if (!_accountBoughtNeco.contains(msg.sender)) { _accountBoughtNeco.add(msg.sender); } emit BuyNecoSuccess(msg.sender, busdAmountRequired, necoAmount); return true; } // claim token. then update user's claim map. function claimToken() external returns(bool) { require(claimEnabled, "Claim has not been started."); require(necoTokenAmountPerAccount[msg.sender] > 0, "You have no NECO token."); uint claimableAmount = necoTokenClaimableAmount(msg.sender); require(claimableAmount > 0, "Your claimable NECO is 0"); if (necoTokenAmountPerAccount[msg.sender] < claimableAmount) { necoToken.transfer(msg.sender, necoTokenAmountPerAccount[msg.sender]); necoTokenAmountPerAccount[msg.sender] = 0; return true; } necoToken.transfer(msg.sender, claimableAmount); necoTokenAmountPerAccount[msg.sender] = necoTokenAmountPerAccount[msg.sender] .sub(claimableAmount); uint currentIndex = getCurrentIndexOfClaim(); for (uint i = 0; i <= currentIndex; i++) { userClaimRoadMap[msg.sender][i] = 0; } emit ClaimSuccess(msg.sender, claimableAmount); return true; } // build a claim roadmap, so that we can know how many tokens users can get accroding to current index. function buildClaimRoadmap(address account) private { uint necoClaimablePerMonth = necoTokenAmountPerAccount[account].mul(2).div(10); for (uint i = 0; i < 5; i ++) { userClaimRoadMap[account][i] = necoClaimablePerMonth; } } // get amount user can claim for current claim index. function necoTokenClaimableAmount(address account) view public returns(uint) { uint currentIndex = getCurrentIndexOfClaim(); uint claimableAmount = 0; for (uint i = 0; i <= currentIndex; i++) { uint claimableAmountOfThisTime = userClaimRoadMap[account][i]; claimableAmount = claimableAmount.add(claimableAmountOfThisTime); } return claimableAmount; } function withdrawRemaining() external onlyOwner { necoToken.transfer(owner(), necoTokenTotalAmount); } function initWhitelist() internal { whitelist[0x3c5de42f02DebBaA235f7a28E4B992362FfeE0B6] = true; _addressSet.add(0x3c5de42f02DebBaA235f7a28E4B992362FfeE0B6); } function getWhitelistAccountAmount() view external returns(uint) { return _addressSet.length(); } function getWhitelistAccountById(uint index) view external returns(address) { return _addressSet.at(index); } function getAccountBoughtNecoLength() view external returns(uint) { return _accountBoughtNeco.length(); } function getAccountBoughtNeco(uint index) view external returns(address) { return _accountBoughtNeco.at(index); } modifier needHaveRemaining() { require(necoTokenTotalAmount > 0, "Oh you are so late."); _; } modifier saleHasStarted() { require(saleStarted, "sale has not been started."); _; } }
set neco token again.
function setNecoTokenPrice(uint newPrice) external onlyOwner { necoTokenPrice = newPrice; }
12,993,689
// File: contracts/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork 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. */ pragma solidity >=0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } // File: contracts/lib/UInt256Lib.sol pragma solidity >=0.4.24; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } // File: contracts/interface/ISeigniorageShares.sol pragma solidity >=0.4.24; interface ISeigniorageShares { function setDividendPoints(address account, uint256 totalDividends) external returns (bool); function mintShares(address account, uint256 amount) external returns (bool); function lastDividendPoints(address who) external view returns (uint256); function externalRawBalanceOf(address who) external view returns (uint256); function externalTotalSupply() external view returns (uint256); } // File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @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. */ 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 use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts/euro/euros.sol pragma solidity >=0.4.24; interface IEuroPolicy { function getEuroSharePrice() external view returns (uint256 price); function treasury() external view returns (address); } /* * Euro ERC20 */ contract Euros is ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogContraction(uint256 indexed epoch, uint256 eurosToBurn); event LogRebasePaused(bool paused); event LogBurn(address indexed from, uint256 value); event LogClaim(address indexed from, uint256 value); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; address public sharesAddress; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } // Precautionary emergency controls. bool public rebasePaused; modifier whenRebaseNotPaused() { require(!rebasePaused); _; } // coins needing to be burned (9 decimals) uint256 private _remainingEurosToBeBurned; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_EURO_SUPPLY = 1 * 10**6 * 10**DECIMALS; uint256 private _maxDiscount; modifier validDiscount(uint256 discount) { require(discount >= 0, 'POSITIVE_DISCOUNT'); // 0% require(discount <= _maxDiscount, 'DISCOUNT_TOO_HIGH'); _; } uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private constant POINT_MULTIPLIER = 10 ** 9; uint256 private _totalDividendPoints; uint256 private _unclaimedDividends; ISeigniorageShares Shares; mapping(address => uint256) private _euroBalances; mapping (address => mapping (address => uint256)) private _allowedEuros; IEuroPolicy EuroPolicy; uint256 public burningDiscount; // percentage (10 ** 9 Decimals) uint256 public defaultDiscount; // discount on first negative rebase uint256 public defaultDailyBonusDiscount; // how much the discount increases per day for consecutive contractions uint256 public minimumBonusThreshold; bool reEntrancyMutex; bool reEntrancyRebaseMutex; address public uniswapV2Pool; mapping(address => bool) deleteWhitelist; event LogDeletion(address account, uint256 amount); bool euroDeletion; modifier onlyMinter() { require(msg.sender == monetaryPolicy || msg.sender == EuroPolicy.treasury(), "Only Minter"); _; } address euroReserve; event LogEuroReserveUpdated(address euroReserve); /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; EuroPolicy = IEuroPolicy(monetaryPolicy_); emit LogMonetaryPolicyUpdated(monetaryPolicy_); } function setEuroReserve(address euroReserve_) external onlyOwner { euroReserve = euroReserve_; emit LogEuroReserveUpdated(euroReserve_); } function mintCash(address account, uint256 amount) external onlyMinter returns (bool) { require(amount != 0, "Invalid Amount"); _totalSupply = _totalSupply.add(amount); _euroBalances[account] = _euroBalances[account].add(amount); // real time claim claimDividends(account); emit Transfer(address(0), account, amount); return true; } function whitelistAddress(address user) external onlyOwner { deleteWhitelist[user] = true; } function removeWhitelistAddress(address user) external onlyOwner { deleteWhitelist[user] = false; } function setEuroDeletion(bool val_) external onlyOwner { euroDeletion = val_; } function setUniswapV2SyncAddress(address uniswapV2Pair_) external onlyOwner { uniswapV2Pool = uniswapV2Pair_; } function setBurningDiscount(uint256 discount) external onlyOwner validDiscount(discount) { burningDiscount = discount; } // amount in is 10 ** 9 decimals function burn(uint256 amount) external updateAccount(msg.sender) { require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); reEntrancyMutex = true; require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE'); require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID'); require(_remainingEurosToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _euroBalances[msg.sender], 'INSUFFICIENT_EURO_BALANCE'); require(amount <= _remainingEurosToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); _burn(msg.sender, amount); reEntrancyMutex = false; } function setDefaultDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDiscount = discount; } function setMaxDiscount(uint256 discount) external onlyOwner { _maxDiscount = discount; } function setDefaultDailyBonusDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDailyBonusDiscount = discount; } /** * @dev Pauses or unpauses the execution of rebase operations. * @param paused Pauses rebase operations if this is true. */ function setRebasePaused(bool paused) external onlyOwner { rebasePaused = paused; emit LogRebasePaused(paused); } // action of claiming funds function claimDividends(address account) public updateAccount(account) returns (uint256) { uint256 owing = dividendsOwing(account); return owing; } function setMinimumBonusThreshold(uint256 minimum) external onlyOwner { require(minimum >= 0, 'POSITIVE_MINIMUM'); require(minimum < _totalSupply, 'MINIMUM_TOO_HIGH'); minimumBonusThreshold = minimum; } function syncUniswapV2() external { uniswapV2Pool.call(abi.encodeWithSignature('sync()')); } /** * @dev Notifies Euros contract about a new rebase cycle. * @param supplyDelta The number of new euro tokens to add into circulation via expansion. * @return The total number of euros after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { reEntrancyRebaseMutex = true; if (supplyDelta == 0) { if (_remainingEurosToBeBurned > minimumBonusThreshold) { burningDiscount = burningDiscount.add(defaultDailyBonusDiscount) > _maxDiscount ? _maxDiscount : burningDiscount.add(defaultDailyBonusDiscount); } else { burningDiscount = defaultDiscount; } emit LogRebase(epoch, _totalSupply); } if (supplyDelta < 0) { uint256 eurosToBurn = uint256(supplyDelta.abs()); if (eurosToBurn > _totalSupply.div(10)) { // maximum contraction is 10% of the total EUR Supply eurosToBurn = _totalSupply.div(10); } if (eurosToBurn.add(_remainingEurosToBeBurned) > _totalSupply) { eurosToBurn = _totalSupply.sub(_remainingEurosToBeBurned); } if (_remainingEurosToBeBurned > minimumBonusThreshold) { burningDiscount = burningDiscount.add(defaultDailyBonusDiscount) > _maxDiscount ? _maxDiscount : burningDiscount.add(defaultDailyBonusDiscount); } else { burningDiscount = defaultDiscount; // default 1% } _remainingEurosToBeBurned = _remainingEurosToBeBurned.add(eurosToBurn); emit LogContraction(epoch, eurosToBurn); } else { disburse(uint256(supplyDelta)); uniswapV2Pool.call(abi.encodeWithSignature('sync()')); emit LogRebase(epoch, _totalSupply); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } } reEntrancyRebaseMutex = false; return _totalSupply; } function initialize(address owner_, address seigniorageAddress) public initializer { ERC20Detailed.initialize("Euros", "EUR", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePaused = false; _totalSupply = INITIAL_EURO_SUPPLY; sharesAddress = seigniorageAddress; Shares = ISeigniorageShares(seigniorageAddress); _euroBalances[owner_] = _totalSupply; _maxDiscount = 50 * 10 ** 9; // 50% defaultDiscount = 1 * 10 ** 9; // 1% burningDiscount = defaultDiscount; defaultDailyBonusDiscount = 1 * 10 ** 9; // 1% minimumBonusThreshold = 100 * 10 ** 9; // 100 euros is the minimum threshold. Anything above warrants increased discount emit Transfer(address(0x0), owner_, _totalSupply); } function dividendsOwing(address account) public view returns (uint256) { if (_totalDividendPoints > Shares.lastDividendPoints(account)) { uint256 newDividendPoints = _totalDividendPoints.sub(Shares.lastDividendPoints(account)); uint256 sharesBalance = Shares.externalRawBalanceOf(account); return sharesBalance.mul(newDividendPoints).div(POINT_MULTIPLIER); } else { return 0; } } // auto claim modifier // if user is owned, we pay out immedietly // if user is not owned, we prevent them from claiming until the next rebase modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { _unclaimedDividends = _unclaimedDividends.sub(owing); if (!deleteWhitelist[account]) { _euroBalances[account] += owing; emit Transfer(address(0), account, owing); } } if (deleteWhitelist[account]) { _delete(account); } Shares.setDividendPoints(account, _totalDividendPoints); emit LogClaim(account, owing); _; } /** * @return The total number of euros. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _euroBalances[who].add(dividendsOwing(who)); } function getRemainingEurosToBeBurned() public view returns (uint256) { return _remainingEurosToBeBurned; } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) updateAccount(msg.sender) updateAccount(to) returns (bool) { require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); if (_euroBalances[msg.sender] > 0 && !deleteWhitelist[to]) { _euroBalances[msg.sender] = _euroBalances[msg.sender].sub(value); _euroBalances[to] = _euroBalances[to].add(value); emit Transfer(msg.sender, to, value); } return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedEuros[owner_][spender]; } function getDeleteWhitelist(address who_) public view returns (bool) { return deleteWhitelist[who_]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) updateAccount(from) updateAccount(msg.sender) updateAccount(to) returns (bool) { require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); if (_euroBalances[from] > 0 && !deleteWhitelist[to]) { _allowedEuros[from][msg.sender] = _allowedEuros[from][msg.sender].sub(value); _euroBalances[from] = _euroBalances[from].sub(value); _euroBalances[to] = _euroBalances[to].add(value); emit Transfer(from, to, value); } return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external validRecipient(spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedEuros[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedEuros[msg.sender][spender] = _allowedEuros[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedEuros[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external updateAccount(spender) updateAccount(msg.sender) returns (bool) { uint256 oldValue = _allowedEuros[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedEuros[msg.sender][spender] = 0; } else { _allowedEuros[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedEuros[msg.sender][spender]); return true; } function consultBurn(uint256 amount) public returns (uint256) { require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE'); require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID'); require(_remainingEurosToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _euroBalances[msg.sender].add(dividendsOwing(msg.sender)), 'INSUFFICIENT_EURO_BALANCE'); require(amount <= _remainingEurosToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); uint256 euroPerShare = EuroPolicy.getEuroSharePrice(); // 1 share = x euros euroPerShare = euroPerShare.sub(euroPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9 uint256 sharesToMint = amount.mul(10 ** 9).div(euroPerShare); // 10^9 return sharesToMint; } function unclaimedDividends() public view returns (uint256) { return _unclaimedDividends; } function totalDividendPoints() public view returns (uint256) { return _totalDividendPoints; } function disburse(uint256 amount) internal returns (bool) { _totalDividendPoints = _totalDividendPoints.add(amount.mul(POINT_MULTIPLIER).div(Shares.externalTotalSupply())); _totalSupply = _totalSupply.add(amount); _unclaimedDividends = _unclaimedDividends.add(amount); return true; } function _delete(address account) internal { uint256 amount = _euroBalances[account]; if (amount > 0) { // master switch if (euroDeletion) { _totalSupply = _totalSupply.sub(amount); _euroBalances[account] = _euroBalances[account].sub(amount); } emit LogDeletion(account, amount); emit Transfer(account, address(0), amount); } } function _burn(address account, uint256 amount) internal { _totalSupply = _totalSupply.sub(amount); _euroBalances[account] = _euroBalances[account].sub(amount); uint256 euroPerShare = EuroPolicy.getEuroSharePrice(); // 1 share = x euros euroPerShare = euroPerShare.sub(euroPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9 uint256 sharesToMint = amount.mul(10 ** 9).div(euroPerShare); // 10^9 _remainingEurosToBeBurned = _remainingEurosToBeBurned.sub(amount); Shares.mintShares(account, sharesToMint); emit Transfer(account, address(0), amount); emit LogBurn(account, amount); } } // File: contracts/interface/IReserve.sol pragma solidity >=0.4.24; interface IReserve { function buyReserveAndTransfer(uint256 mintAmount) external; } // File: contracts/euro/eurosPolicy.sol pragma solidity >=0.4.24; /* * Euro Policy */ interface IDecentralizedOracle { function update() external; function consult(address token, uint amountIn) external view returns (uint amountOut); } contract EurosPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); Euros public euros; // Provides the current CPI, as an 18 decimal fixed point number. IDecentralizedOracle public sharesPerEuroOracle; IDecentralizedOracle public ethPerEuroOracle; IDecentralizedOracle public ethPerEurocOracle; uint256 public deviationThreshold; uint256 public rebaseLag; uint256 private cpi; uint256 public minRebaseTimeIntervalSec; uint256 public lastRebaseTimestampSec; uint256 public rebaseWindowOffsetSec; uint256 public rebaseWindowLengthSec; uint256 public epoch; address public WETH_ADDRESS; address public SHARE_ADDRESS; uint256 private constant DECIMALS = 18; uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; address public orchestrator; bool private initializedOracle; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } uint256 public minimumEuroCirculation; uint256 public constant MAX_SLIPPAGE_PARAM = 1180339 * 10**2; // max ~20% market impact uint256 public constant MAX_MINT_PERC_PARAM = 25 * 10**7; // max 25% of rebase can go to treasury uint256 public rebaseMintPerc; uint256 public maxSlippageFactor; address public treasury; address public public_goods; uint256 public public_goods_perc; event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); function getEuroSharePrice() external view returns (uint256) { uint256 sharePrice = sharesPerEuroOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals return sharePrice; } function initializeReserve(address treasury_) external onlyOwner returns (bool) { maxSlippageFactor = 5409258 * 10; // 5.4% = 10 ^ 9 base rebaseMintPerc = 10 ** 8; // 10% treasury = treasury_; return true; } function mint(uint256 amount_) external onlyOwner { euros.mintCash(msg.sender, amount_); } function rebase() external onlyOrchestrator { require(inRebaseWindow(), "OUTISDE_REBASE"); require(initializedOracle == true, 'ORACLE_NOT_INITIALIZED'); require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "MIN_TIME_NOT_MET"); lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); sharesPerEuroOracle.update(); ethPerEuroOracle.update(); ethPerEurocOracle.update(); uint256 ethEurocPrice = ethPerEurocOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^18 decimals ropsten, 10^6 mainnet uint256 ethEuroPrice = ethPerEuroOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^9 decimals uint256 euroCoinExchangeRate = ethEurocPrice.mul(10 ** 9) // 10^18 decimals, 10**9 ropsten, 10**21 on mainnet .div(ethEuroPrice); uint256 sharePrice = sharesPerEuroOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals uint256 shareExchangeRate = sharePrice.mul(euroCoinExchangeRate).div(10 ** 18); // 10^18 decimals uint256 targetRate = cpi; if (euroCoinExchangeRate > MAX_RATE) { euroCoinExchangeRate = MAX_RATE; } // euroCoinExchangeRate & targetRate arre 10^18 decimals int256 supplyDelta = computeSupplyDelta(euroCoinExchangeRate, targetRate); // supplyDelta = 10^9 decimals // // Apply the Dampening factor. // // supplyDelta = supplyDelta.mul(10 ** 9).div(rebaseLag.toInt256Safe()); uint256 algorithmicLag_ = getAlgorithmicRebaseLag(supplyDelta); require(algorithmicLag_ > 0, "algorithmic rate must be positive"); rebaseLag = algorithmicLag_; supplyDelta = supplyDelta.mul(10 ** 9).div(algorithmicLag_.toInt256Safe()); // v 0.0.1 // check on the expansionary side if (supplyDelta > 0 && euros.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(euros.totalSupply())).toInt256Safe(); } // check on the contraction side if (supplyDelta < 0 && euros.getRemainingEurosToBeBurned().add(uint256(supplyDelta.abs())) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(euros.getRemainingEurosToBeBurned())).toInt256Safe(); } // set minimum floor if (supplyDelta < 0 && euros.totalSupply().sub(euros.getRemainingEurosToBeBurned().add(uint256(supplyDelta.abs()))) < minimumEuroCirculation) { supplyDelta = (euros.totalSupply().sub(euros.getRemainingEurosToBeBurned()).sub(minimumEuroCirculation)).toInt256Safe(); } uint256 supplyAfterRebase; if (supplyDelta < 0) { // contraction, we send the amount of shares to mint uint256 eurosToBurn = uint256(supplyDelta.abs()); supplyAfterRebase = euros.rebase(epoch, (eurosToBurn).toInt256Safe().mul(-1)); } else { // expansion, we send the amount of euros to mint supplyAfterRebase = euros.rebase(epoch, supplyDelta); uint256 treasuryAmount = uint256(supplyDelta).mul(rebaseMintPerc).div(10 ** 9); uint256 supplyDeltaMinusTreasury = uint256(supplyDelta).sub(treasuryAmount); supplyAfterRebase = euros.rebase(epoch, (supplyDeltaMinusTreasury).toInt256Safe()); if (treasuryAmount > 0) { // call reserve swap IReserve(treasury).buyReserveAndTransfer(treasuryAmount); } } assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, euroCoinExchangeRate, cpi, supplyDelta, now); } function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } function setPublicGoods(address public_goods_, uint256 public_goods_perc_) external onlyOwner { public_goods = public_goods_; public_goods_perc = public_goods_perc_; } function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } function setCpi(uint256 cpi_) external onlyOwner { require(cpi_ > 0); cpi = cpi_; } function getCpi() external view returns (uint256) { return cpi; } function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } function initializeOracles( address sharesPerEuroOracleAddress, address ethPerEuroOracleAddress, address ethPerEurocOracleAddress ) external onlyOwner { require(initializedOracle == false, 'ALREADY_INITIALIZED_ORACLE'); sharesPerEuroOracle = IDecentralizedOracle(sharesPerEuroOracleAddress); ethPerEuroOracle = IDecentralizedOracle(ethPerEuroOracleAddress); ethPerEurocOracle = IDecentralizedOracle(ethPerEurocOracleAddress); initializedOracle = true; } function changeOracles( address sharesPerEuroOracleAddress, address ethPerEuroOracleAddress, address ethPerEurocOracleAddress ) external onlyOwner { sharesPerEuroOracle = IDecentralizedOracle(sharesPerEuroOracleAddress); ethPerEuroOracle = IDecentralizedOracle(ethPerEuroOracleAddress); ethPerEurocOracle = IDecentralizedOracle(ethPerEurocOracleAddress); } function setWethAddress(address wethAddress) external onlyOwner { WETH_ADDRESS = wethAddress; } function setShareAddress(address shareAddress) external onlyOwner { SHARE_ADDRESS = shareAddress; } function setMinimumEuroCirculation(uint256 minimumEuroCirculation_) external onlyOwner { minimumEuroCirculation = minimumEuroCirculation_; } function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } function initialize(address owner_, Euros euros_) public initializer { Ownable.initialize(owner_); deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 50 * 10 ** 9; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 63000; // with stock market, 63000 for 1:30pm EST (debug) rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; cpi = 1 * 10 ** 18; epoch = 0; minimumEuroCirculation = 1000000 * 10 ** 9; // 1M minimum euro circulation euros = euros_; } // takes current marketcap of EURO and calculates the algorithmic rebase lag // returns 10 ** 9 rebase lag factor function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) { if (euros.totalSupply() >= 30000000 * 10 ** 9) { return 30 * 10 ** 9; } else { require(euros.totalSupply() > 1000000 * 10 ** 9, "MINIMUM EURO SUPPLY NOT MET"); if (supplyDelta < 0) { uint256 eurosToBurn = uint256(supplyDelta.abs()); // 1.238453076e15 return uint256(100 * 10 ** 9).sub((euros.totalSupply().sub(1000000 * 10 ** 9)).div(500000)); } else { return uint256(29).mul(euros.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9); } } } function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyOwner { require(maxSlippageFactor_ < MAX_SLIPPAGE_PARAM); uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyOwner { require(rebaseMintPerc_ < MAX_MINT_PERC_PARAM); uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } int256 targetRateSigned = targetRate.toInt256Safe(); return euros.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } }
Decrease the amount of tokens that an owner has allowed to a spender. spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by./
{ uint256 oldValue = _allowedEuros[msg.sender][spender]; function approve(address spender, uint256 value) external validRecipient(spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) } function increaseAllowance(address spender, uint256 addedValue) external updateAccount(msg.sender) updateAccount(spender) returns (bool) } function decreaseAllowance(address spender, uint256 subtractedValue) external updateAccount(spender) updateAccount(msg.sender) returns (bool) if (subtractedValue >= oldValue) { _allowedEuros[msg.sender][spender] = 0; _allowedEuros[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedEuros[msg.sender][spender]); return true; } else { }
6,605,015
pragma solidity ^0.4.4; contract FirstContract { bool frozen = false; address owner; function FirstContract() payable { owner = msg.sender; } function freeze() { frozen = true; } //Release balance back to original owner if any function releaseFunds() { owner.transfer(this.balance); } //You can claim current balance if you put the same amount (or more) back in function claimBonus() payable { if ((msg.value >= this.balance) && (frozen == false)) { msg.sender.transfer(this.balance); } } }
You can claim current balance if you put the same amount (or more) back in
function claimBonus() payable { if ((msg.value >= this.balance) && (frozen == false)) { msg.sender.transfer(this.balance); } }
12,965,418
//SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @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); } /* * @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; } } /** * @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. */ 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 () public{ address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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) { 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; } } /** * @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) public _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 public _totalSupply; string private _name; string private _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 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 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 { } } /** * @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 { using SafeMath for uint256; /** * @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 { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } /** * @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) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // 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"); } /** * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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]. */ 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 // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () public { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract Operator is Context, Ownable { address private _operator; event OperatorTransferred( address indexed previousOperator, address indexed newOperator ); constructor() public{ _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); } function operator() public view returns (address) { return _operator; } modifier onlyOperator() { require( _operator == msg.sender, 'operator: caller is not the operator' ); _; } function isOperator() public view returns (bool) { return _msgSender() == _operator; } function transferOperator(address newOperator_) public onlyOwner { _transferOperator(newOperator_); } function _transferOperator(address newOperator_) internal { require( newOperator_ != address(0), 'operator: zero address given for new operator' ); emit OperatorTransferred(address(0), newOperator_); _operator = newOperator_; } } contract Share is ERC20Burnable, Operator, ReentrancyGuard { using SafeMath for uint256; address public governance; address public firstBeneficiary; address public secondBeneficiary; uint256 public beneficiaryFeePercent = 0; // 2500 == 0.2500% modifier onlyGovernance() { require(msg.sender == governance); _; } constructor(address _governance) public ERC20('YFL Synthetic', 'sYFL') { governance = _governance; _totalSupply = 5000000 * 10**18; _balances[msg.sender] = 2500000 * 10**18; _balances[governance] = 2500000 * 10**18; } function burn(uint256 amount) public override onlyOperator nonReentrant { super.burn(amount); } function burnFrom(address account, uint256 amount) public override onlyOperator nonReentrant { super.burnFrom(account, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual override nonReentrant { uint256 transferAmount = amount; if(beneficiaryFeePercent != 0) { uint256 beneficiaryFeeSplit = transferAmount.mul(beneficiaryFeePercent) / 2000000; // Split beneficiary fee if(firstBeneficiary != address(0)) { transferAmount = transferAmount.sub(beneficiaryFeeSplit); super._transfer(sender, firstBeneficiary, beneficiaryFeeSplit); } if(secondBeneficiary != address(0)) { transferAmount = transferAmount.sub(beneficiaryFeeSplit); super._transfer(sender, secondBeneficiary, beneficiaryFeeSplit); } } super._transfer(sender, recipient, transferAmount); } function setBeneficiaryFeePercent(uint256 _beneficiaryFeePercent) external onlyGovernance { // max 1% require(_beneficiaryFeePercent <= 10000, "Beneficiary Fee Percentage: too high"); beneficiaryFeePercent = _beneficiaryFeePercent; } function setFirstBeneficiary(address _beneficiary) external onlyGovernance { firstBeneficiary = _beneficiary; } function setSecondBeneficiary(address _beneficiary) external onlyGovernance { secondBeneficiary = _beneficiary; } }
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 { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); }
162,531
pragma solidity 0.4.19; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract MarginlessToken is ERC20, Ownable { using SafeMath for uint256; string public constant name = "Marginless Token"; string public constant symbol = "MRS"; uint8 public constant decimals = 18; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) internal allowed; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; uint256 private totalSupply_; modifier canTransfer() { require(mintingFinished); _; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public canTransfer returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @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 */ function transferFrom(address _from, address _to, uint256 _value) public canTransfer returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract TokenDeskProxySupport { function buyTokens(address sender_, address benefeciary_, uint256 tokenDeskBonus_) external payable; } contract TokenDeskProxyAware is TokenDeskProxySupport, Ownable { address private tokenDeskProxy; modifier onlyTokenDeskProxy() { require(msg.sender == tokenDeskProxy); _; } function buyTokens(address beneficiary) public payable { internalBuyTokens(msg.sender, beneficiary, 0); } function buyTokens(address sender, address beneficiary, uint256 tokenDeskBonus) external payable onlyTokenDeskProxy { internalBuyTokens(sender, beneficiary, tokenDeskBonus); } function setTokenDeskProxy(address tokenDeskProxy_) public onlyOwner { require(tokenDeskProxy_ != address(0)); tokenDeskProxy = tokenDeskProxy_; } function internalBuyTokens(address sender, address beneficiary, uint256 tokenDeskBonus) internal; } /** * The EscrowVault contract collects crowdsale ethers and allows to refund * if softcap soft cap is not reached. */ contract EscrowVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, GoalReached, Closed } mapping (address => uint256) public deposited; address public beneficiary; address public superOwner; State public state; event GoalReached(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); event Withdrawal(uint256 weiAmount); event Close(); function EscrowVault(address _superOwner, address _beneficiary) public { require(_beneficiary != address(0)); require(_superOwner != address(0)); beneficiary = _beneficiary; superOwner = _superOwner; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active || state == State.GoalReached); deposited[investor] = deposited[investor].add(msg.value); } function setGoalReached() onlyOwner public { require (state == State.Active); state = State.GoalReached; GoalReached(); } function withdraw(uint256 _amount) public { require(msg.sender == superOwner); require(state == State.GoalReached); require (_amount <= this.balance && _amount > 0); beneficiary.transfer(_amount); Withdrawal(_amount); } function withdrawAll() onlyOwner public { require(state == State.GoalReached); uint256 balance = this.balance; Withdrawal(balance); beneficiary.transfer(balance); } function close() onlyOwner public { require (state == State.GoalReached); withdrawAll(); state = State.Closed; Close(); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract MarginlessCrowdsale is TokenDeskProxyAware { using SafeMath for uint256; // Wallet where all ether will be moved after escrow withdrawal. Can be even multisig wallet address public constant WALLET = 0x5081D48973e3c00e30fa03556d9bF04A1b7AD162; // Wallet for team tokens address public constant TEAM_WALLET = 0x886dBF3DF6FAC78DFcb1cb89fff040FEAA5F7b2A; // Wallet for Airdrop/referall/affiliate tokens address public constant AIRDROP_WALLET = 0x71eAa00654Bc33fE41DA1499DEb618Dc1f4A5De9; // Wallet for company tokens address public constant COMPANY_WALLET = 0xC42476A4BA45841CA27a37fbD309EE8Aaf22c886; // Wallet for jackpot tokens address public constant JACKPOT_WALLET = 0x846198eC3Ff77F8CdDf7D0C5a1B46656367711db; uint256 public constant TEAM_TOKENS_LOCK_PERIOD = 60 * 60 * 24 * 365; // 365 days uint256 public constant COMPANY_TOKENS_LOCK_PERIOD = 60 * 60 * 24 * 180; // 180 days uint256 public constant SOFT_CAP = 40000000e18; // 40 000 000 uint256 public constant ICO_TOKENS = 210000000e18; // 210 000 000 uint256 public constant START_TIME = 1523268000; // 2018/04/09 10:00 UTC +0 uint256 public constant RATE = 10000; // 0.0001 ETH uint256 public constant LARGE_PURCHASE = 12500e18; // 12 500 tokens uint256 public icoEndTime = 1527760800; // 2018/05/31 10:00 UTC +0 uint8 public constant ICO_TOKENS_PERCENT = 70; uint8 public constant TEAM_TOKENS_PERCENT = 10; uint8 public constant COMPANY_TOKENS_PERCENT = 10; uint8 public constant AIRDROP_TOKENS_PERCENT = 5; uint8 public constant JACKPOT_TOKENS_PERCENT = 5; uint8 public constant LARGE_PURCHASE_BONUS = 5; Stage[] internal stages; struct Stage { uint256 cap; uint64 till; uint8 bonus; } // The token being sold MarginlessToken public token; // amount of raised money in wei uint256 public weiRaised; // refund vault used to hold funds while crowdsale is running EscrowVault public vault; uint256 public currentStage = 0; bool public isFinalized = false; address private tokenMinter; TokenTimelock public teamTimelock; TokenTimelock public companyTimelock; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); /** * When there no tokens left to mint and token minter tries to manually mint tokens * this event is raised to signal how many tokens we have to charge back to purchaser */ event ManualTokenMintRequiresRefund(address indexed purchaser, uint256 value); function MarginlessCrowdsale(address _token) public { stages.push(Stage({ till: 1523440800, bonus: 29, cap: 40000000e18 })); // 2018/04/11 10:00 UTC +0 stages.push(Stage({ till: 1523786400, bonus: 25, cap: 170000000e18 })); // 2018/04/15 10:00 UTC +0 stages.push(Stage({ till: 1525082400, bonus: 20, cap: 0 })); // 2018/04/30 10:00 UTC +0 stages.push(Stage({ till: 1526292000, bonus: 10, cap: 0 })); // 2018/05/14 10:00 UTC +0 stages.push(Stage({ till: 1527760800, bonus: 0, cap: 0 })); // 2018/05/31 10:00 UTC +0 stages.push(Stage({ till: ~uint64(0), bonus: 0, cap: 0 })); // unlimited token = MarginlessToken(_token); vault = new EscrowVault(msg.sender, WALLET); // Wallet where all ether will be stored during ICO } modifier onlyTokenMinterOrOwner() { require(msg.sender == tokenMinter || msg.sender == owner); _; } function internalBuyTokens(address sender, address beneficiary, uint256 tokenDeskBonus) internal { require(beneficiary != address(0)); require(sender != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 nowTime = getNow(); // this loop moves stages and ensures correct stage according to date while (currentStage < stages.length && stages[currentStage].till < nowTime) { // move all unsold tokens to next stage uint256 nextStage = currentStage.add(1); stages[nextStage].cap = stages[nextStage].cap.add(stages[currentStage].cap); stages[currentStage].cap = 0; currentStage = nextStage; } // calculate token amount to be created uint256 tokens = calculateTokens(weiAmount, tokenDeskBonus); uint256 excess = appendContribution(beneficiary, tokens); uint256 refund = (excess > 0 ? excess.mul(weiAmount).div(tokens) : 0); weiAmount = weiAmount.sub(refund); weiRaised = weiRaised.add(weiAmount); if (refund > 0) { // hard cap reached, no more tokens to mint sender.transfer(refund); } TokenPurchase(sender, beneficiary, weiAmount, tokens.sub(excess)); if (goalReached() && vault.state() == EscrowVault.State.Active) { vault.setGoalReached(); } vault.deposit.value(weiAmount)(sender); } function calculateTokens(uint256 _weiAmount, uint256 _tokenDeskBonus) internal view returns (uint256) { uint256 tokens = _weiAmount.mul(RATE); if (stages[currentStage].bonus > 0) { uint256 stageBonus = tokens.mul(stages[currentStage].bonus).div(100); tokens = tokens.add(stageBonus); } if (currentStage < 2) return tokens; uint256 bonus = _tokenDeskBonus.add(tokens >= LARGE_PURCHASE ? LARGE_PURCHASE_BONUS : 0); return tokens.add(tokens.mul(bonus).div(100)); } function appendContribution(address _beneficiary, uint256 _tokens) internal returns (uint256) { uint256 excess = _tokens; uint256 tokensToMint = 0; while (excess > 0 && currentStage < stages.length) { Stage storage stage = stages[currentStage]; if (excess >= stage.cap) { excess = excess.sub(stage.cap); tokensToMint = tokensToMint.add(stage.cap); stage.cap = 0; currentStage = currentStage.add(1); } else { stage.cap = stage.cap.sub(excess); tokensToMint = tokensToMint.add(excess); excess = 0; } } if (tokensToMint > 0) { token.mint(_beneficiary, tokensToMint); } return excess; } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = getNow() >= START_TIME && getNow() <= icoEndTime; bool nonZeroPurchase = msg.value != 0; bool canMint = token.totalSupply() < ICO_TOKENS; bool validStage = (currentStage < stages.length); return withinPeriod && nonZeroPurchase && canMint && validStage; } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(getNow() > icoEndTime || token.totalSupply() == ICO_TOKENS); if (goalReached()) { // Close escrowVault and transfer all collected ethers into WALLET address if (vault.state() != EscrowVault.State.Closed) { vault.close(); } uint256 totalSupply = token.totalSupply(); teamTimelock = new TokenTimelock(token, TEAM_WALLET, getNow().add(TEAM_TOKENS_LOCK_PERIOD)); token.mint(teamTimelock, uint256(TEAM_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT)); companyTimelock = new TokenTimelock(token, COMPANY_WALLET, getNow().add(COMPANY_TOKENS_LOCK_PERIOD)); token.mint(companyTimelock, uint256(COMPANY_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT)); token.mint(AIRDROP_WALLET, uint256(AIRDROP_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT)); token.mint(JACKPOT_WALLET, uint256(JACKPOT_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT)); token.finishMinting(); token.transferOwnership(token); } else { vault.enableRefunds(); } Finalized(); isFinalized = true; } function goalReached() public view returns (bool) { return token.totalSupply() >= SOFT_CAP; } // fallback function can be used to buy tokens or claim refund function () external payable { if (!isFinalized) { buyTokens(msg.sender); } else { claimRefund(); } } function mintTokens(address[] _receivers, uint256[] _amounts) external onlyTokenMinterOrOwner { require(_receivers.length > 0 && _receivers.length <= 100); require(_receivers.length == _amounts.length); require(!isFinalized); for (uint256 i = 0; i < _receivers.length; i++) { address receiver = _receivers[i]; uint256 amount = _amounts[i]; require(receiver != address(0)); require(amount > 0); uint256 excess = appendContribution(receiver, amount); if (excess > 0) { ManualTokenMintRequiresRefund(receiver, excess); } } } function setIcoEndTime(uint256 _endTime) public onlyOwner { require(_endTime > START_TIME && _endTime > getNow()); icoEndTime = _endTime; } function setTokenMinter(address _tokenMinter) public onlyOwner { require(_tokenMinter != address(0)); tokenMinter = _tokenMinter; } function getNow() internal view returns (uint256) { return now; } }
Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
437,743
pragma solidity ^0.4.21; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface token { function transfer(address receiver, uint amount) external; } contract Crowdsale is owned { address public beneficiary; uint public fundingGoal; uint public amountRaised; uint public durationOfStage; uint public priceStage1; uint public priceStage2; token public tokenReward; mapping(address => uint256) public balanceOf; uint deadlineOfStage; bool stage1End = false; bool crowdsaleClosed = false; event Closed(address recipient, uint totalAmountRaised); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constructor function * * Setup the owner */ function Crowdsale( address ifSuccessfulSendTo, uint fundingGoalInEthers, uint durationInMinutes, uint tokenCostInEthStg1, uint tokenCostInEthStg2, address addressOfTokenUsedAsReward ) public { beneficiary = ifSuccessfulSendTo; fundingGoal = fundingGoalInEthers * 1 ether; durationOfStage = durationInMinutes * 1 minutes; priceStage1 = tokenCostInEthStg1 * 1 ether; priceStage2 = tokenCostInEthStg2 * 1 ether; tokenReward = token(addressOfTokenUsedAsReward); deadlineOfStage = now + durationInMinutes * 1 minutes; } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () payable public { require(!crowdsaleClosed); uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; if(!stage1End) { tokenReward.transfer(msg.sender, amount / priceStage1); emit FundTransfer(msg.sender, amount, true); } else { tokenReward.transfer(msg.sender, amount / priceStage2); emit FundTransfer(msg.sender, amount, true); } if(amountRaised >= fundingGoal) { crowdsaleClosed = true; emit Closed(beneficiary, amountRaised); } } /** * Change stage if deadline reached * * Checks if the deadline of any stage reached and changes stage, if both reached - crowdsale close */ function changeStage() onlyOwner public { require(!crowdsaleClosed); if (!stage1End){ if(now >= deadlineOfStage){ stage1End = true; deadlineOfStage = now + durationOfStage; } } else { if(now >= deadlineOfStage) { crowdsaleClosed = true; emit Closed(beneficiary, amountRaised); } } } /** * Withdraw the funds * * Checks if crowdsale was closed (hardcap or time limit has been reached) and if so * sends the entire amount to the beneficiary. Contributors can't withdraw the amount * they contributed - preICO does not provide refund. */ function withdrawal() public { if (crowdsaleClosed && (beneficiary == msg.sender)) { if (beneficiary.send(amountRaised)) { emit FundTransfer(beneficiary, amountRaised, false); } } } }
Withdraw the funds Checks if crowdsale was closed (hardcap or time limit has been reached) and if so sends the entire amount to the beneficiary. Contributors can't withdraw the amount they contributed - preICO does not provide refund./
function withdrawal() public { if (crowdsaleClosed && (beneficiary == msg.sender)) { if (beneficiary.send(amountRaised)) { emit FundTransfer(beneficiary, amountRaised, false); } } }
12,858,331
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IHswapV2Callee { function hswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } interface IMdexFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeToRate() external view returns (uint256); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setFeeToRate(uint256) external; function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1); function pairFor(address tokenA, address tokenB) external view returns (address pair); function getReserves(address tokenA, address tokenB) external view returns (uint256 reserveA, uint256 reserveB); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IMdexPair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function price(address token, uint256 baseDecimal) external view returns (uint256); function initialize(address, address) external; } contract MdexERC20 { using SafeMath for uint256; string public constant name = 'HSwap LP Token'; string public constant symbol = 'HMDX'; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); constructor() public { uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external returns (bool) { if (allowance[from][msg.sender] != uint256(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, 'MdexSwap: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'MdexSwap: INVALID_SIGNATURE'); _approve(owner, spender, value); } } contract MdexPair is MdexERC20 { using SafeMath for uint256; using UQ112x112 for uint224; uint256 public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint256 private unlocked = 1; modifier lock() { require(unlocked == 1, 'MdexSwap: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer( address token, address to, uint256 value ) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'MdexSwap: TRANSFER_FAILED'); } event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'MdexSwap: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update( uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1 ) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'MdexSwap: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IMdexFactory(factory).feeTo(); feeOn = feeTo != address(0); uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = SafeMath.sqrt(uint256(_reserve0).mul(_reserve1)); uint256 rootKLast = SafeMath.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(IMdexFactory(factory).feeToRate()).add(rootKLast); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint256 liquidity) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); uint256 amount0 = balance0.sub(_reserve0); uint256 amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = SafeMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'MdexSwap: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint256 amount0, uint256 amount1) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint256 balance0 = IERC20(_token0).balanceOf(address(this)); uint256 balance1 = IERC20(_token1).balanceOf(address(this)); uint256 liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'MdexSwap: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external lock { require(amount0Out > 0 || amount1Out > 0, 'MdexSwap: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'MdexSwap: INSUFFICIENT_LIQUIDITY'); uint256 balance0; uint256 balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'MdexSwap: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IHswapV2Callee(to).hswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'MdexSwap: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2), 'MdexSwap: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } function price(address token, uint256 baseDecimal) public view returns (uint256) { if ((token0 != token && token1 != token) || 0 == reserve0 || 0 == reserve1) { return 0; } if (token0 == token) { return uint256(reserve1).mul(baseDecimal).div(uint256(reserve0)); } else { return uint256(reserve0).mul(baseDecimal).div(uint256(reserve1)); } } } contract MdexFactory { using SafeMath for uint256; address public feeTo; address public feeToSetter; uint256 public feeToRate; bytes32 public initCodeHash; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint256); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; initCodeHash = keccak256(abi.encodePacked(type(MdexPair).creationCode)); } function allPairsLength() external view returns (uint256) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(tokenA != tokenB, 'MdexSwapFactory: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'MdexSwapFactory: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'MdexSwapFactory: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(MdexPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IMdexPair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external { require(msg.sender == feeToSetter, 'MdexSwapFactory: FORBIDDEN'); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external { require(msg.sender == feeToSetter, 'MdexSwapFactory: FORBIDDEN'); require(_feeToSetter != address(0), 'MdexSwapFactory: FeeToSetter is zero address'); feeToSetter = _feeToSetter; } function setFeeToRate(uint256 _rate) external { require(msg.sender == feeToSetter, 'MdexSwapFactory: FORBIDDEN'); require(_rate > 0, 'MdexSwapFactory: FEE_TO_RATE_OVERFLOW'); feeToRate = _rate.sub(1); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) public pure returns (address token0, address token1) { require(tokenA != tokenB, 'MdexSwapFactory: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'MdexSwapFactory: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address tokenA, address tokenB) public view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint256(keccak256(abi.encodePacked(hex'ff', address(this), keccak256(abi.encodePacked(token0, token1)), initCodeHash)))); } // fetches and sorts the reserves for a pair function getReserves(address tokenA, address tokenB) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IMdexPair(pairFor(tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure returns (uint256 amountB) { require(amountA > 0, 'MdexSwapFactory: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'MdexSwapFactory: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public pure returns (uint256 amountOut) { require(amountIn > 0, 'MdexSwapFactory: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'MdexSwapFactory: INSUFFICIENT_LIQUIDITY'); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public pure returns (uint256 amountIn) { require(amountOut > 0, 'MdexSwapFactory: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'MdexSwapFactory: INSUFFICIENT_LIQUIDITY'); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(uint256 amountIn, address[] memory path) public view returns (uint256[] memory amounts) { require(path.length >= 2, 'MdexSwapFactory: INVALID_PATH'); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(uint256 amountOut, address[] memory path) public view returns (uint256[] memory amounts) { require(path.length >= 2, 'MdexSwapFactory: INVALID_PATH'); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } library SafeMath { uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wad() public pure returns (uint256) { return WAD; } function ray() public pure returns (uint256) { return RAY; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function sqrt(uint256 a) internal pure returns (uint256 b) { if (a > 3) { b = a; uint256 x = a / 2 + 1; while (x < b) { b = x; x = (a / x + x) / 2; } } else if (a != 0) { b = 1; } } function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / WAD; } function wmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function rmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / RAY; } function rmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), RAY / 2) / RAY; } function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, WAD), b); } function wdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, RAY), b); } function rdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, RAY), b / 2) / b; } function wpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = WAD; while (n > 0) { if (n % 2 != 0) { result = wmul(result, x); } x = wmul(x, x); n /= 2; } return result; } function rpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = RAY; while (n > 0) { if (n % 2 != 0) { result = rmul(result, x); } x = rmul(x, x); n /= 2; } return result; } }
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure returns (uint256 amountB) { require(amountA > 0, 'MdexSwapFactory: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'MdexSwapFactory: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
14,092,443
pragma solidity ^0.5.0; contract Bank { address manager; struct customer { string name; uint age; uint256 blocknumber; string region; string typeofAccount; } customer[] public customerlist; uint public custCount; mapping(address=>uint) public balances; event transfer(address to,uint amount); event bal(uint amount); constructor()public { manager=msg.sender; custCount=0; } modifier onlyManager() { require(msg.sender==manager,"you are not the manager"); _; } /* In order to open the account you have to send minimum 1 ether when you call the function**/ function openAccount(string memory _name,uint _age,string memory _region,string memory _typeofAccount)public payable { require(msg.value >100000000,"insufficient amount"); customerlist.push(customer(_name,_age,block.number,_region,_typeofAccount)); custCount++; balances[msg.sender]=msg.value; emit bal(msg.value); } /*In order to withdraw amount from your account you need to have suffiecient balance which is stored in the balances mapping the amount has to be specified in wei **/ function withdraw(uint amount)public{ require(amount<=balances[msg.sender],"insufficient balance"); balances[msg.sender]=balances[msg.sender]-amount; msg.sender.transfer(amount); } /* You can add money to your account by calling the deposit function and its payable **/ function deposit()public payable{ balances[msg.sender]=balances[msg.sender]+msg.value; } /*You can transfer amount from your account to any ethereum address by specifying the amount **/ function transferto(uint amount,address payable reciever)public{ require(amount<=balances[msg.sender],"insufficient balance"); balances[msg.sender]=balances[msg.sender]-amount; reciever.transfer(amount); emit transfer(reciever,amount); } /* The person who deployed the contract is the manager and only he can call this function to check the total amount present in the bank **/ function checkbalanceofbank() public onlyManager view returns(uint){ return(address(this).balance); } /* This is a private function which is internally called by the callBalance and returns the Userbalance **/ function Userbalance(address from) private view returns(uint){ return(balances[from]); } /* This is used to the private function Userbalance **/ function callBalance(address from) public view returns(uint){ uint balance=Userbalance(from); return balance; } }
In order to withdraw amount from your account you need to have suffiecient balance which is stored in the balances mapping the amount has to be specified in wei /
function withdraw(uint amount)public{ require(amount<=balances[msg.sender],"insufficient balance"); balances[msg.sender]=balances[msg.sender]-amount; msg.sender.transfer(amount); }
5,522,452
./partial_match/1/0xA06fcD43EB625566747B9EF7c3BBD6e866944cc8/sources/MonksOfEleusis.sol
the minus and plus 1 ensures this is between 1 and maxSupply because mod will return 0
function getOffsetTokenId(uint256 tokenId) public view returns (uint256) { return (((tokenId - 1 + mTokenOffset) % cMaxSupply) + 1); }
15,768,994
/** *Submitted for verification at Etherscan.io on 2022-03-16 */ // SPDX-License-Identifier: MIT /** * @title T.O.T.A Contract by 7K Labs - Props to Chiru Labs for that erc721A goodness * * __________________________________________________________ * /\____/\\\\\\\\\\\\\\\___/\\\______/\\\_____/\\\___________\ * \/\___\/////////////\\\__\/\\\____/\\\/_____\/\\\___________\ * \/\______________/\\\/___\/\\\__/\\\/_______\/\\\___________\ * \/\____________/\\\/_____\/\\\/\\\/_________\/\\\___________\ * \/\__________/\\\/_______\/\\\\/\\\_________\/\\\___________\ * \/\________/\\\/_________\/\\\\///\\\_______\/\\\___________\ * \/\______/\\\/___________\/\\\__\///\\\_____\/\\\___________\ * \/\____/\\\/_____________\/\\\____\///\\\___\/\\\\\\\\\\\\\_\ * \/\___\///_______________\///_______\///____\/////////////__\ * \/\_________________________________________________________\ * \/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ * */ // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol // 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. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ 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 Merkle 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) } } } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @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); } } // File: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @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); } // File: https://github.com/chiru-labs/ERC721A/blob/main/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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 { _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 { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } pragma solidity >=0.7.0 <0.9.0; contract TribesOfTheAftermathTOTA is ERC721A, Ownable { using Strings for uint256; string internal contractName = "Tribes of the Aftermath TOTA"; string internal contractAbbr = "TOTA"; string public uriPrefix = ""; string public uriSuffix = ""; string public hiddenMetadataUri = "ipfs://QmQF6vN693xtnbtGNw4HVT6UdmQKuxvDxe59dG8w3NzaHv/tota.json"; bool public isRevealed = false; uint256 public preSaleCost = 0.08 ether; uint256 public pubSaleCost = 0.08 ether; uint256 public maxPreSalePerWallet = 5; uint256 public maxPubSalePerWallet = 20; uint256 public maxMintAmountPerTx = 10; uint256 public maxSupply = 8888; uint256 private ownerMintOnDeployment = 1; uint256 private ownerReserved = 150; bool public isSaleActive = false; bool public isPreSaleActive = true; // 0 = bypass, 1 = off-chain, 2 = on-chain uint256 public preSaleType = 1; address[] internal whitelistedAddresses; bytes32 public merkleRoot = 0xc6d7e6e2d994b666611235bdf1714dc30f20b966386a81ce610273f349dedb39; // team wallet addresses address internal raWallet = 0xe23D436Fc2F715d2B4Ec402511965E1474699fc9; address internal jrWallet = 0x6E035e0Dbd225E97AA171b87902ce6fe8527f16C; address internal tmWallet = 0xDac0B32df6DCFE658Af3bd1Fdf0c95D2af0b678A; address internal dgWallet = 0x6d587352dF7e0C377E87983586459609e9baf94e; address internal scWallet = 0xa130D1133Ef1A84F39B84467b16f5A0DD0577d4A; address internal spWallet = 0x56df8E01CC2fE2e1e01f6A0ee9B79c5aE54f3560; address internal devWallet = 0x1C81E289886544A04691936B13570e9B35495746; address internal teamWallet = 0x1C5b3F89D3Acf80223E2484897D2e38cF61E7c20; constructor() ERC721A(contractName, contractAbbr) { setHiddenMetadataUri(hiddenMetadataUri); _safeMint(teamWallet, ownerMintOnDeployment); } /** * @dev keeps track of the wallets that have minted during the whitelist and how many tokens they have minted */ struct Minter { bool exists; uint256 hasMintedByWhitelist; uint256 hasMintedInPublicSale; } mapping(address => Minter) public minters; /** * @dev public mint function takes in the amount of tokens to mint */ function mintPubSale(uint256 _mintAmount) public payable { require(isSaleActive, "Sale is not active!"); require(!isPreSaleActive, "Pre Sale is active!"); require(totalSupply() + _mintAmount <= maxSupply - ownerReserved, "Max supply exceeded!"); require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(msg.value >= pubSaleCost * _mintAmount, "Insufficient funds!"); require( minters[msg.sender].hasMintedInPublicSale + _mintAmount <= maxPubSalePerWallet, "Exceeds per wallet limit." ); if (!minters[msg.sender].exists) minters[msg.sender].exists = true; minters[msg.sender].hasMintedInPublicSale = minters[msg.sender].hasMintedInPublicSale + _mintAmount; _safeMint(msg.sender, _mintAmount); } /** * @dev presale mint function takes in the amount of tokens to mint and the proof for the merkel tree * if the merkle tree is not being used then feed in an empty array ([]) or if doing it from * etherscan feed in 0x0000000000000000000000000000000000000000000000000000000000000000 */ function mintPreSale(uint256 _mintAmount, bytes32[] calldata _markleProof) public payable { require(isSaleActive, "Sale is not active!"); require(totalSupply() + _mintAmount <= maxSupply - ownerReserved, "Max supply exceeded!"); require(isPreSaleActive, "Pre Sale is not active!"); require(msg.value >= preSaleCost * _mintAmount, "Insufficient funds!"); require(_mintAmount > 0, "Invalid mint amount!"); require(_mintAmount <= maxPreSalePerWallet, "Exceeds per wallet presale limit."); if (preSaleType == 1) require(isWhitelistedByMerkle(_markleProof, msg.sender), "You are not whitelisted."); if (preSaleType == 2) require(isWhitelistedByAddress(msg.sender), "You are not whitelisted."); require( minters[msg.sender].hasMintedByWhitelist + _mintAmount <= maxPreSalePerWallet, "Exceeds per wallet presale limit." ); if (!minters[msg.sender].exists) minters[msg.sender].exists = true; minters[msg.sender].hasMintedByWhitelist = minters[msg.sender].hasMintedByWhitelist + _mintAmount; _safeMint(msg.sender, _mintAmount); } /** * @dev returns an array of token IDs that the wallet owns */ function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 0; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } /** * @dev tests whether the wallet address has been whitelisted by the merkle tree by verifying * the proof provided to the function */ function isWhitelistedByMerkle(bytes32[] calldata _markleProof, address _user) public view returns(bool) { bytes32 leaf = keccak256(abi.encodePacked(_user)); return MerkleProof.verify(_markleProof, merkleRoot, leaf); } /** * @dev tests whether the wallet address has been whitelisted by the checking the whitelistedAddresses * array and returning a true/false flag */ function isWhitelistedByAddress(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } /** * @dev a simple `is whitelisted` function which tests the following things * 1) is the sale is active and the presale not active (public sale is active) - returns true * 2) presale type is 1 (merkle tree) - calls the isWhitelistedByMerkle() function * 3) presale type is 2 (standard whitelist) - calls the isWhitelistedByAddress() function * 4) if the above is not met, then return false */ function isWhitelisted(bytes32[] calldata _markleProof, address _user) public view returns(bool) { if (isSaleActive && !isPreSaleActive) { return true; } if (preSaleType == 0) { return true; } if (preSaleType == 1) { return isWhitelistedByMerkle(_markleProof, _user); } if (preSaleType == 2) { return isWhitelistedByAddress(_user); } return false; } /** * @dev returns all whitelisted addresses in an array */ function getWhitelistAddresses() public view returns(address[] memory) { return whitelistedAddresses; } /** * @dev returns the token URI - will return the hidden metadata if the isRevealed state is false */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId),"ERC721Metadata: URI query for nonexistent token"); if (isRevealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } /** * @dev returns the base token sufix */ function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } /** * @dev returns the remaining public supply */ function getRemainingPublicSupply() public view returns (uint256) { return maxSupply - ownerReserved - totalSupply(); } /** * @dev returns the remaining reserved supply */ function getRemainingReservedSupply() public view returns (uint256) { return ownerReserved; } // // only owner functions /** * @dev sets the presale type - 1 is merkle tree validation and 2 is standard whitelist array */ function setPreSaleType(uint8 _type) public onlyOwner { // 0 = bypass whitelist, 1 = merkle tree, 2 = wl addresses require(_type == 0 || _type == 1 || _type == 2, "Invalid whitelist type."); preSaleType = _type; } /** * @dev sets the merkle root for the verification (wl type 1) */ function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } /** * @dev sets the array for the whitelists (wl type 2) * this will reset the original whitelist with whatever is set here. therefore the entire * whitelist needs to be provided again */ function setWhitelistAddresses(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } /** * @dev allows the contract owner to manually mint a set amount to a specified wallet address * where only the gas needs to be paid. these tokens come out of the public supply */ function sendPublicTokenToAddr(uint256 _mintAmount, address _receiver) public onlyOwner { require(totalSupply() + _mintAmount <= maxSupply - ownerReserved, "Max supply exceeded!"); require(_mintAmount > 0, "Invalid mint amount"); _safeMint(_receiver, _mintAmount); } /** * @dev allows the contract owner to manually mint a set amount to a specified wallet address * where only the gas needs to be paid. these tokens come out of the reserved/non-public supply */ function sendReservedTokenToAddr(uint256 _mintAmount, address _receiver) public onlyOwner { require(ownerReserved > 0 && _mintAmount <= ownerReserved, "Exceeds reserved supply!"); require(_mintAmount > 0, "Invalid mint amount"); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); setReservedSupply(ownerReserved - _mintAmount); _safeMint(_receiver, _mintAmount); } /** * @dev allows the contract owner to change the amount they have reserved */ function setReservedSupply(uint256 _amount) public onlyOwner { require(_amount >= 0 && _amount <= maxSupply - totalSupply(), "Exceeds remaining supply!"); ownerReserved = _amount; } /** * @dev flips the revealed state from false to true. it can be flipped back but all metadata on OpenSea * would need to be refresed again. */ function flipRevealedState() public onlyOwner { isRevealed = !isRevealed; } /** * @dev sets the presale price of the token. this has to be sent through in wei and not eth * eg 1 eth = 1000000000000000000 wei */ function setPreSaleCost(uint256 _cost) public onlyOwner { preSaleCost = _cost; } /** * @dev sets the public sale price of the token. this has to be sent through in wei and not eth * eg 1 eth = 1000000000000000000 wei */ function setPubSaleCost(uint256 _cost) public onlyOwner { pubSaleCost = _cost; } /** * @dev sets the max amount per transaction in the public sale */ function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } /** * @dev sets the max amount per wallet in the presale */ function setMaxPreSalePerWallet(uint256 _maxMintAmount) public onlyOwner { require(_maxMintAmount > 0, "Must be greater than zero"); maxPreSalePerWallet = _maxMintAmount; } /** * @dev sets the max amount per wallet in the public sale */ function setMaxPubSalePerWallet(uint256 _maxMintAmount) public onlyOwner { require(_maxMintAmount > 0, "Must be greater than zero"); maxPubSalePerWallet = _maxMintAmount; } /** * @dev sets the not revealed metadata path (if using ipfs if must be entered ipfs://<CID>/hidden.json) */ function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } /** * @dev sets the path to the token (if using ipfs if must be entered ipfs://<CID>/) with the trailing slash * an api can just be called as eg https://api.myurl.com/token/ */ function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } /** * @dev sets the uri suffix (ie if the metadata is stored on ipfs this should be set to .json) */ function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } /** * @dev sets the uri suffix to blank if it has been set and you want to use an api to call your metadata */ function setUriSuffixToBlank() public onlyOwner { uriSuffix = ""; } /** * @dev sets the sale state (either true to false or false to true) this must be set to true for any * public minting to occur (even the presale) */ function flipSaleState() public onlyOwner { isSaleActive = !isSaleActive; } /** * @dev sets the presale state (either true to false or false to true) this must be set to true for any * presale functionality to occur) */ function flipPreSaleState() public onlyOwner { isPreSaleActive = !isPreSaleActive; } /** * @dev called to withdraw funds from the contract. this will pay x% to a developer wallet and the remaining balance * to the contract owner. the dev wallet and % are set at the top of this contract */ function withdraw() public onlyOwner { uint256 _balance = address(this).balance; (bool ra, ) = payable(raWallet).call{value: _balance * 14 / 100}(""); require(ra); (bool jr, ) = payable(jrWallet).call{value: _balance * 28 / 100}(""); require(jr); (bool tm, ) = payable(tmWallet).call{value: _balance * 3 / 100}(""); require(tm); (bool dg, ) = payable(dgWallet).call{value: _balance * 4 / 100}(""); require(dg); (bool sc, ) = payable(scWallet).call{value: _balance * 15 / 100}(""); require(sc); (bool sp, ) = payable(spWallet).call{value: _balance * 8 / 100}(""); require(sp); (bool dw, ) = payable(devWallet).call{value: _balance * 10 / 100}(""); require(dw); (bool tw, ) = payable(teamWallet).call{value: address(this).balance}(""); require(tw); } }
returns all whitelisted addresses in an array/
function getWhitelistAddresses() public view returns(address[] memory) { return whitelistedAddresses; }
10,965,960
pragma solidity ^0.5.12; import "./MixTokenInterface.sol"; import "./MixTokenItemRegistry.sol"; /** * @title MixTokenBurn * @author Jonathan Brown <[email protected]> * @dev Enable accounts to burn their tokens. */ contract MixTokenBurn { /** * @dev Amount of tokens burned, linked to next most burned. */ struct AccountBurnedLinked { address next; uint amount; } /** * @dev Mapping of item to token to burn for that item. */ mapping (bytes32 => MixTokenOwnedInterface) itemTokenToBurn; /** * @dev Mapping of token to list of items that it should be burned for. */ mapping (address => bytes32[]) tokenToBurnItemsList; /** * @dev Mapping of account to list of tokens that it has burned. */ mapping (address => MixTokenInterface[]) accountTokensBurnedList; /** * @dev Mapping of token to mapping of account to AccountBurnedLinked. */ mapping (address => mapping (address => AccountBurnedLinked)) tokenAccountBurned; /** * @dev Mapping of account to list of itemIds that it has burned the token for. */ mapping (address => bytes32[]) accountItemsBurnedList; /** * @dev Mapping of itemId to mapping of account to quantity of tokens burned for the item. */ mapping (bytes32 => mapping (address => AccountBurnedLinked)) itemAccountBurned; /** * @dev Mapping of item to total burned for the item. */ mapping (bytes32 => uint) itemBurnedTotal; /** * @dev MixItemStoreRegistry contract. */ MixItemStoreRegistry public itemStoreRegistry; /** * @dev Address of token registry contract. */ MixTokenItemRegistry public tokenItemRegistry; /** * @dev A token has been burned. * @param token Address of the token's contract. * @param itemId Item the token was burned for, or 0 for none. * @param account Address of the account burning its tokens. * @param amount Amount of tokens burned. */ event BurnToken(MixTokenInterface indexed token, bytes32 indexed itemId, address indexed account, uint amount); /** * @dev Revert if amount is zero. * @param amount Amount that must not be zero. */ modifier nonZero(uint amount) { require (amount != 0, "Amount burned must not be zero."); _; } /** * @param _itemStoreRegistry Address of the MixItemStoreRegistry contract. * @param _tokenItemRegistry Address of the MixTokenItemRegistry contract. */ constructor(MixItemStoreRegistry _itemStoreRegistry, MixTokenItemRegistry _tokenItemRegistry) public { // Store the address of the MixItemStoreRegistry contract. itemStoreRegistry = _itemStoreRegistry; // Store the address of the MixTokenItemRegistry contract. tokenItemRegistry = _tokenItemRegistry; } /** * @dev Set the token that can be burned for an item. * @param itemId itemId of item that is having set which token can be burned for it. * @param token Address of token that can be burned for the item. */ function setTokenToBurnItem(bytes32 itemId, MixTokenOwnedInterface token) external { MixItemStoreInterface itemStore = itemStoreRegistry.getItemStore(itemId); // Ensure the item is owned by sender. require (itemStore.getOwner(itemId) == msg.sender, "Item is not owned by sender."); // Ensure the token is owned by sender. require (token.owner() == msg.sender, "Token is not owned by sender."); // Ensure the item's token has not been set before. require (itemTokenToBurn[itemId] == MixTokenOwnedInterface(0), "Token to burn for item has already been set."); // Set the token to burn for the item. itemTokenToBurn[itemId] = token; // Add item to list of items that burn token. tokenToBurnItemsList[address(token)].push(itemId); } /** * @dev Get previous and old previous accounts for inserting into linked list. * @param accountBurned Linked list of how much each account has burned. * @param amount Amount that the the new entry will have. * @return prev Address of the entry preceeding the new entry. * @return oldPrev Address of the entry preceeding the old entry. */ function _getPrev(mapping (address => AccountBurnedLinked) storage accountBurned, uint amount) internal view nonZero(amount) returns (address prev, address oldPrev) { // Get sender AccountBurnedLinked. AccountBurnedLinked storage senderBurned = accountBurned[msg.sender]; // Get total. uint total = senderBurned.amount + amount; // Search for first account that has burned less than sender. address next = accountBurned[address(0)].next; // accountBurned[0].amount == 0 while (total <= accountBurned[next].amount) { prev = next; next = accountBurned[next].next; } // Is sender already in the list? if (senderBurned.amount > 0) { // Search for account. oldPrev = prev; while (accountBurned[oldPrev].next != msg.sender) { oldPrev = accountBurned[oldPrev].next; } } } /** * @dev Get previous and old previous accounts for inserting burned tokens into tokenAccountBurned linked list. * @param token Token that is being burned. * @param amount Amount of the token that is being burned. * @return prev Address of the entry preceeding the new entry. * @return oldPrev Address of the entry preceeding the old entry. */ function getBurnTokenPrev(MixTokenInterface token, uint amount) external view returns (address prev, address oldPrev) { (prev, oldPrev) = _getPrev(tokenAccountBurned[address(token)], amount); } /** * @dev Get previous and old previous accounts for inserting burned tokens for an item into both tokenAccountBurned and itemAccountBurned linked lists. * @param itemId Item having its token burned. * @param amount Amount of the token that is being burned. * @return tokenPrev Address of the entry preceeding the new entry in the tokenAccountBurned linked list. * @return tokenOldPrev Address of the entry preceeding the old entry in the tokenAccountBurned linked list. * @return itemPrev Address of the entry preceeding the new entry in the itemAccountBurned linked list. * @return itemOldPrev Address of the entry preceeding the old entry in the itemAccountBurned linked list. */ function getBurnItemPrev(bytes32 itemId, uint amount) external view returns (address tokenPrev, address tokenOldPrev, address itemPrev, address itemOldPrev) { // Get token contract for item. address token = address(getTokenToBurnItem(itemId)); // Get previous and old previous for tokenAccountBurned linked list. (tokenPrev, tokenOldPrev) = _getPrev(tokenAccountBurned[token], amount); // Get previous and old previous for itemAccountBurned linked list. (itemPrev, itemOldPrev) = _getPrev(itemAccountBurned[itemId], amount); } /** * @dev Insert amount burned into linked list. * @param accountBurned Linked list of how much each account has burned. * @param amount Amount of tokens burned. * @param prev Address of the entry preceeding the new entry. * @param oldPrev Address of the entry preceeding the old entry. */ function _accountBurnedInsert(mapping (address => AccountBurnedLinked) storage accountBurned, uint amount, address prev, address oldPrev) internal { // Get sender AccountBurnedLinked. AccountBurnedLinked storage senderBurned = accountBurned[msg.sender]; // Get total. uint total = senderBurned.amount + amount; // Check supplied new previous. if (prev != address(0)) { require (total <= accountBurned[prev].amount, "Total burned must be less than or equal to previous account."); } // Find correct previous. Search for first account that has burned less than sender. address next = accountBurned[prev].next; // accountBurned[0].amount == 0 while (total <= accountBurned[next].amount) { prev = next; next = accountBurned[prev].next; } bool replace = false; // Is sender already in the list? if (senderBurned.amount > 0) { // Find correct old previous. while (accountBurned[oldPrev].next != msg.sender) { oldPrev = accountBurned[oldPrev].next; require(oldPrev != address(0), "Old previous account incorrect."); } // Is it in the same position? if (prev == oldPrev) { replace = true; } else { // Remove sender from current position. accountBurned[oldPrev].next = senderBurned.next; } } if (!replace) { // Insert into linked list. accountBurned[prev].next = msg.sender; senderBurned.next = next; } // Update the amount. senderBurned.amount = total; } /** * @dev Record burning of tokens in linked list. * @param token Address of token being burned. * @param amount Amount of token being burned. * @param prev Address of the entry preceeding the new entry. * @param oldPrev Address of the entry preceeding the old entry. */ function _burnToken(MixTokenInterface token, uint amount, address prev, address oldPrev) internal { // Get accountBurned mapping. mapping (address => AccountBurnedLinked) storage accountBurned = tokenAccountBurned[address(token)]; // Update list of tokens burned by this account. if (accountBurned[msg.sender].amount == 0) { accountTokensBurnedList[msg.sender].push(token); } _accountBurnedInsert(accountBurned, amount, prev, oldPrev); } /** * @dev Record burning of tokens for item in linked list. * @param itemId Item having its token burned. * @param amount Amount of token being burned. * @param prev Address of the entry preceeding the new entry. * @param oldPrev Address of the entry preceeding the old entry. */ function _burnItem(bytes32 itemId, uint amount, address prev, address oldPrev) internal { // Get accountBurned mapping. mapping (address => AccountBurnedLinked) storage accountBurned = itemAccountBurned[itemId]; // Update list of items burned by this account. if (accountBurned[msg.sender].amount == 0) { accountItemsBurnedList[msg.sender].push(itemId); } _accountBurnedInsert(accountBurned, amount, prev, oldPrev); } /** * @dev Burn sender's tokens. * @param token Address of the token's contract. * @param amount Amount of tokens burned. * @param prev Address of the entry preceeding the new entry. * @param oldPrev Address of the entry preceeding the old entry. */ function burnToken(MixTokenInterface token, uint amount, address prev, address oldPrev) external nonZero(amount) { // Transfer the tokens to this contract. // Wrap with require () in case the token contract returns false on error instead of throwing. require (token.transferFrom(msg.sender, address(this), amount), "Token transfer failed."); // Record the tokens as burned. _burnToken(token, amount, prev, oldPrev); // Emit the event. emit BurnToken(token, 0, msg.sender, amount); } /** * @dev Burn sender's tokens for a specific item. * @param itemId Item to burn this token for. * @param amount Amount of tokens burned. * @param tokenPrev Address of the entry preceeding the new entry in the tokenAccountBurned linked list. * @param tokenOldPrev Address of the entry preceeding the old entry in the tokenAccountBurned linked list. * @param itemPrev Address of the entry preceeding the new entry in the itemAccountBurned linked list. * @param itemOldPrev Address of the entry preceeding the old entry in the itemAccountBurned linked list. */ function burnItem(bytes32 itemId, uint amount, address tokenPrev, address tokenOldPrev, address itemPrev, address itemOldPrev) external nonZero(amount) { // Get token contract for item. MixTokenInterface token = MixTokenInterface(address(getTokenToBurnItem(itemId))); // Transfer the tokens to this contract. // Wrap with require () in case the token contract returns false on error instead of throwing. require (token.transferFrom(msg.sender, address(this), amount), "Token transfer failed."); // Record the tokens as burned. _burnToken(token, amount, tokenPrev, tokenOldPrev); _burnItem(itemId, amount, itemPrev, itemOldPrev); // Update total burned for this item. itemBurnedTotal[itemId] += amount; // Emit the event. emit BurnToken(token, itemId, msg.sender, amount); } /** * @dev Get the token that can be burned for an item. * @param itemId itemId of the item. * @return Token that can be burned for the item. */ function getTokenToBurnItem(bytes32 itemId) public view returns (MixTokenOwnedInterface token) { token = itemTokenToBurn[itemId]; require (token != MixTokenOwnedInterface(0), "Item does not have a token to burn."); } /** * @dev Get number of items that a token can be burned for. * @param token Token to get the number of items that can be burned for. * @return Number of items that the token can be burned for. */ function getItemsBurningTokenCount(MixTokenInterface token) external view returns (uint) { return tokenToBurnItemsList[address(token)].length; } /** * @dev Get list of items that a token can be burned for. * @param token Token to check which items it can be burned tokens for. * @param offset Offset to start results from. * @param limit Maximum number of results to return. 0 for unlimited. * @return itemIds List of itemIds for items token can be burned for. * @return amounts Amount of tokens that was burned for each item. */ function getItemsBurningToken(MixTokenInterface token, uint offset, uint limit) external view returns (bytes32[] memory itemIds, uint[] memory amounts) { // Get itemsBurningToken mapping. bytes32[] storage itemsBurningToken = tokenToBurnItemsList[address(token)]; uint _limit = 0; // Check if offset is beyond the end of the array. if (offset < itemsBurningToken.length) { // Check how many itemIds we can retrieve. if (limit == 0 || offset + limit > itemsBurningToken.length) { _limit = itemsBurningToken.length - offset; } else { _limit = limit; } } // Allocate memory arrays. itemIds = new bytes32[](_limit); amounts = new uint[](_limit); // Populate memory array. for (uint i = 0; i < _limit; i++) { itemIds[i] = itemsBurningToken[offset + i]; amounts[i] = itemBurnedTotal[itemIds[i]]; } } /** * @dev Get the amount of tokens an account has burned. * @param account Address of the account. * @param token Address of the token contract. * @return Amount of these tokens that this account has burned. */ function getAccountTokenBurned(address account, MixTokenInterface token) external view returns (uint) { return tokenAccountBurned[address(token)][account].amount; } /** * @dev Get the amount of tokens an account has burned for an item. * @param account Address of the account. * @param itemId Item to get the amount of tokens account has burned for it. * @return Amount of these tokens that this account has burned for the item. */ function getAccountItemBurned(address account, bytes32 itemId) external view returns (uint) { return itemAccountBurned[itemId][account].amount; } /** * @dev Get number of different tokens an account has burned. * @param account Account to get the number of different tokens burned. * @return Number of different tokens account has burned. */ function getAccountTokensBurnedCount(address account) external view returns (uint) { return accountTokensBurnedList[account].length; } /** * @dev Get list of tokens that an account has burned. * @param account Account to get which tokens it has burned. * @param offset Offset to start results from. * @param limit Maximum number of results to return. 0 for unlimited. * @return tokens List of tokens the account has burned. * @return amounts Amount of each token that was burned by account. */ function getAccountTokensBurned(address account, uint offset, uint limit) external view returns (address[] memory tokens, uint[] memory amounts) { // Get tokensBurned mapping. MixTokenInterface[] storage tokensBurned = accountTokensBurnedList[account]; uint _limit = 0; // Check if offset is beyond the end of the array. if (offset < tokensBurned.length) { // Check how many itemIds we can retrieve. if (limit == 0 || offset + limit > tokensBurned.length) { _limit = tokensBurned.length - offset; } else { _limit = limit; } } // Allocate memory arrays. tokens = new address[](_limit); amounts = new uint[](_limit); // Populate memory arrays. for (uint i = 0; i < _limit; i++) { tokens[i] = address(tokensBurned[offset + i]); amounts[i] = tokenAccountBurned[tokens[i]][account].amount; } } /** * @dev Get accounts that have burned. * @param accountBurned Linked list of how much each account has burned. * @param offset Offset to start results from. * @param limit Maximum number of results to return. * @return accounts List of accounts that burned the token. * @return amounts Amount of token each account burned. */ function _getAccountsBurned(mapping (address => AccountBurnedLinked) storage accountBurned, uint offset, uint limit) internal view returns (address[] memory accounts, uint[] memory amounts) { // Find the account at offset. address account = accountBurned[address(0)].next; uint i = 0; while (account != (address(0)) && i++ < offset) { account = accountBurned[account].next; } // Check how many accounts we can retrieve. address _account = account; uint _limit = 0; while (_account != address(0) && _limit < limit) { _account = accountBurned[_account].next; _limit++; } // Allocate return variables. accounts = new address[](_limit); amounts = new uint[](_limit); // Populate return variables. i = 0; while (i < _limit) { accounts[i] = account; amounts[i++] = accountBurned[account].amount; account = accountBurned[account].next; } } /** * @dev Get accounts that have burned a token. * @param token Token to get accounts that have burned it. * @param offset Offset to start results from. * @param limit Maximum number of results to return. * @return accounts List of accounts that burned the token. * @return amounts Amount of token each account burned. */ function getTokenAccountsBurned(MixTokenInterface token, uint offset, uint limit) external view returns (address[] memory accounts, uint[] memory amounts) { // Get accountBurned mapping. mapping (address => AccountBurnedLinked) storage accountBurned = tokenAccountBurned[address(token)]; // Get accounts and corresponding amounts. (accounts, amounts) = _getAccountsBurned(accountBurned, offset, limit); } /** * @dev Get number of items an account has burned tokens for. * @param account Account to check. * @return Number of items account has burned tokens for. */ function getAccountItemsBurnedCount(address account) external view returns (uint) { return accountItemsBurnedList[account].length; } /** * @dev Get list of items that an account has burned tokens for. * @param account Account to check which items it has burned tokens for. * @param offset Offset to start results from. * @param limit Maximum number of results to return. 0 for unlimited. * @return itemIds List of itemIds for items account has burned tokens for. * @return amounts Amount of each token that was burned for each item by account. */ function getAccountItemsBurned(address account, uint offset, uint limit) external view returns (bytes32[] memory itemIds, uint[] memory amounts) { // Get itemsBurned mapping. bytes32[] storage itemsBurned = accountItemsBurnedList[account]; uint _limit = 0; // Check if offset is beyond the end of the array. if (offset < itemsBurned.length) { // Check how many itemIds we can retrieve. if (limit == 0 || offset + limit > itemsBurned.length) { _limit = itemsBurned.length - offset; } else { _limit = limit; } } // Allocate memory arrays. itemIds = new bytes32[](_limit); amounts = new uint[](_limit); // Populate memory array. for (uint i = 0; i < _limit; i++) { itemIds[i] = itemsBurned[offset + i]; amounts[i] = itemAccountBurned[itemIds[i]][account].amount; } } /** * @dev Get accounts that have burned tokens for an item. * @param itemId Item to get accounts for. * @param offset Offset to start results from. * @param limit Maximum number of results to return. * @return accounts List of accounts that burned tokens for the item. * @return amounts Amount of token each account burned for the item. */ function getItemAccountsBurned(bytes32 itemId, uint offset, uint limit) external view returns (address[] memory accounts, uint[] memory amounts) { // Get accountBurned mapping. mapping (address => AccountBurnedLinked) storage accountBurned = itemAccountBurned[itemId]; // Get accounts and corresponding amounts. (accounts, amounts) = _getAccountsBurned(accountBurned, offset, limit); } /** * @dev Get total amount of tokens that were burned for an item. * @param itemId Item to get amount of tokens burned for. * @return Total amount of tokens that have been burned for the item. */ function getItemBurnedTotal(bytes32 itemId) external view returns (uint) { return itemBurnedTotal[itemId]; } }
Get the amount of tokens an account has burned. account Address of the account. token Address of the token contract. return Amount of these tokens that this account has burned./
function getAccountTokenBurned(address account, MixTokenInterface token) external view returns (uint) { return tokenAccountBurned[address(token)][account].amount; }
5,447,943
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract ProofOfExistence { mapping(bytes32 => bool) private proofs; /// @notice store a proof of existence in the contract state /// @param proof to store function storeProof(bytes32 proof) internal { proofs[proof] = true; } /// @notice calculate and store the proof for a document /// @param document to store function notarize(string calldata document) external { bytes32 proof = proofFor(document); storeProof(proof); } /// @notice helper function to get a document's sha256 /// @param document to validate /// @return document hash function proofFor(string memory document) public pure returns (bytes32) { return keccak256(bytes(document)); } /// @notice check if a document has been notarized /// @param document to validate /// @return proof of existence function checkDocument(string memory document) public view returns (bool) { bytes32 proof = proofFor(document); return hasProof(proof); } /// @notice returns true if proof is stored /// @param proof to validate /// @return proof of existence function hasProof(bytes32 proof) internal view returns (bool) { return proofs[proof]; } }
helper function to get a document's sha256 document to validate return document hash
function proofFor(string memory document) public pure returns (bytes32) { return keccak256(bytes(document)); }
14,082,094
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interface/ISFIRewarder.sol"; contract SaffronERC20Staking is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; uint256 rewardDebt; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SFIs to distribute per block. uint256 lastRewardBlock; // Last block number that SFIs distribution occurs. uint256 accSFIPerShare; // Accumulated SFIs per share, times 1e12. See below. } // The SFI TOKEN! IERC20 public sfi; // SFI tokens created per block. uint256 public sfiPerBlock; uint256 public rewardEndBlock; address public rewardDistributor; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _sfi, address _rewardDistributor, uint256 _sfiPerBlock ) public { sfi = _sfi; rewardDistributor = _rewardDistributor; sfiPerBlock = _sfiPerBlock; } function updateRewardDistributor(address _newRewardDistributor) external onlyOwner { require(_newRewardDistributor != address(0), "invalid address"); rewardDistributor = _newRewardDistributor; } function setRewardPerBlock(uint256 _sfiPerBlock) external onlyOwner { require(_sfiPerBlock > 0, "invalid sfiperblock"); sfiPerBlock = _sfiPerBlock; } function setRewardEndBlock(uint256 _endblock) external onlyOwner { require(_endblock > 0, "invalid block number"); rewardEndBlock = _endblock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: block.number, accSFIPerShare: 0}) ); } function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function pendingSFI(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSFIPerShare = pool.accSFIPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); uint256 currentBlock = block.number; if (rewardEndBlock != 0 && block.number >= rewardEndBlock) currentBlock = rewardEndBlock; if (currentBlock > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = currentBlock.sub(pool.lastRewardBlock); uint256 sfiReward = multiplier.mul(sfiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSFIPerShare = accSFIPerShare.add(sfiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSFIPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (rewardEndBlock != 0 && block.number >= rewardEndBlock) currentBlock = rewardEndBlock; if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 multiplier = currentBlock.sub(pool.lastRewardBlock); uint256 sfiReward = multiplier.mul(sfiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accSFIPerShare = pool.accSFIPerShare.add(sfiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = currentBlock; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSFIPerShare).div(1e12).sub(user.rewardDebt); safeSFITransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSFIPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSFIPerShare).div(1e12).sub(user.rewardDebt); safeSFITransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSFIPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sfi transfer function, just in case if rounding error causes pool to not have enough SFIs. function safeSFITransfer(address _to, uint256 _amount) internal { if (_amount > 0) ISFIRewarder(rewardDistributor).supplyRewards(_to, _amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 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] = toDeleteIndex + 1; // All indexes are 1-based // 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // 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); } // 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)))); } // 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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) { 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) { // 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) { 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) { 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) { 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) { require(b <= a, "SafeMath: subtraction overflow"); 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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); 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) { require(b > 0, "SafeMath: modulo by zero"); 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) { 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. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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) { 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) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ISFIRewarder { function supplyRewards(address to, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // 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"); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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; } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (rewardEndBlock != 0 && block.number >= rewardEndBlock) currentBlock = rewardEndBlock; if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 multiplier = currentBlock.sub(pool.lastRewardBlock); uint256 sfiReward = multiplier.mul(sfiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accSFIPerShare = pool.accSFIPerShare.add(sfiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = currentBlock; }
13,413,647
// SPDX-License-Identifier: MIT pragma solidity >=0.6.10 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../utils/SafeDecimalMath.sol"; import "../utils/CoreUtility.sol"; import "../interfaces/IPrimaryMarket.sol"; import "../interfaces/IFund.sol"; import "../interfaces/ITwapOracle.sol"; import "../interfaces/IAprOracle.sol"; import "../interfaces/IBallot.sol"; import "../interfaces/IVotingEscrow.sol"; import "../interfaces/ITrancheIndex.sol"; import "./FundRoles.sol"; contract Fund is IFund, Ownable, ReentrancyGuard, FundRoles, CoreUtility, ITrancheIndex { using Math for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; uint256 private constant UNIT = 1e18; uint256 private constant MAX_INTEREST_RATE = 0.2e18; // 20% daily uint256 private constant MAX_DAILY_PROTOCOL_FEE_RATE = 0.05e18; // 5% daily rate uint256 private constant WEIGHT_A = 1; uint256 private constant WEIGHT_B = 1; uint256 private constant WEIGHT_M = WEIGHT_A + WEIGHT_B; /// @notice Upper bound of `NAV_B / NAV_A` to trigger a rebalance. uint256 public immutable upperRebalanceThreshold; /// @notice Lower bound of `NAV_B / NAV_A` to trigger a rebalance. uint256 public immutable lowerRebalanceThreshold; /// @notice Address of the underlying token. address public immutable override tokenUnderlying; /// @notice A multipler that normalizes an underlying balance to 18 decimal places. uint256 public immutable override underlyingDecimalMultiplier; /// @notice Daily protocol fee rate. uint256 public dailyProtocolFeeRate; /// @notice TwapOracle address for the underlying asset. ITwapOracle public override twapOracle; /// @notice AprOracle address. IAprOracle public aprOracle; /// @notice Address of the interest rate ballot. IBallot public ballot; /// @notice Fee Collector address. address public override feeCollector; /// @notice Address of Token M. address public override tokenM; /// @notice Address of Token A. address public override tokenA; /// @notice Address of Token B. address public override tokenB; /// @notice End timestamp of the current trading day. /// A trading day starts at UTC time `SETTLEMENT_TIME` of a day (inclusive) /// and ends at the same time of the next day (exclusive). uint256 public override currentDay; /// @notice Start timestamp of the current primary market activity window. uint256 public override fundActivityStartTime; /// @notice Start timestamp of the current exchange activity window. uint256 public override exchangeActivityStartTime; uint256 public activityDelayTimeAfterRebalance; /// @dev Historical rebalances. Rebalances are often accessed in loops with bounds checking. /// So we store them in a fixed-length array, in order to make compiler-generated /// bounds checking on every access cheaper. The actual length of this array is stored in /// `_rebalanceSize` and should be explicitly checked when necessary. Rebalance[65535] private _rebalances; /// @dev Historical rebalance count. uint256 private _rebalanceSize; /// @dev Total share supply of the three tranches. They are always rebalanced to the latest /// version. uint256[TRANCHE_COUNT] private _totalSupplies; /// @dev Mapping of account => share balance of the three tranches. /// Rebalance versions are stored in a separate mapping `_balanceVersions`. mapping(address => uint256[TRANCHE_COUNT]) private _balances; /// @dev Rebalance version mapping for `_balances`. mapping(address => uint256) private _balanceVersions; /// @dev Mapping of owner => spender => share allowance of the three tranches. /// Rebalance versions are stored in a separate mapping `_allowanceVersions`. mapping(address => mapping(address => uint256[TRANCHE_COUNT])) private _allowances; /// @dev Rebalance version mapping for `_allowances`. mapping(address => mapping(address => uint256)) private _allowanceVersions; /// @dev Mapping of trading day => NAV tuple. mapping(uint256 => uint256[TRANCHE_COUNT]) private _historicalNavs; /// @notice Mapping of trading day => total fund shares. /// /// Key is the end timestamp of a trading day. Value is the total fund shares after /// settlement of that trading day, as if all Token A and B are merged. mapping(uint256 => uint256) public override historicalTotalShares; /// @notice Mapping of trading day => underlying assets in the fund. /// /// Key is the end timestamp of a trading day. Value is the underlying assets in /// the fund after settlement of that trading day. mapping(uint256 => uint256) public historicalUnderlying; /// @notice Mapping of trading week => interest rate of Token A. /// /// Key is the end timestamp of a trading week. Value is the interest rate captured /// after settlement of the last day of the previous trading week. mapping(uint256 => uint256) public historicalInterestRate; address[] private obsoletePrimaryMarkets; address[] private newPrimaryMarkets; constructor( address tokenUnderlying_, uint256 underlyingDecimals_, uint256 dailyProtocolFeeRate_, uint256 upperRebalanceThreshold_, uint256 lowerRebalanceThreshold_, address twapOracle_, address aprOracle_, address ballot_, address feeCollector_ ) public Ownable() FundRoles() { tokenUnderlying = tokenUnderlying_; require(underlyingDecimals_ <= 18, "Underlying decimals larger than 18"); underlyingDecimalMultiplier = 10**(18 - underlyingDecimals_); require( dailyProtocolFeeRate_ <= MAX_DAILY_PROTOCOL_FEE_RATE, "Exceed max protocol fee rate" ); dailyProtocolFeeRate = dailyProtocolFeeRate_; upperRebalanceThreshold = upperRebalanceThreshold_; lowerRebalanceThreshold = lowerRebalanceThreshold_; twapOracle = ITwapOracle(twapOracle_); aprOracle = IAprOracle(aprOracle_); ballot = IBallot(ballot_); feeCollector = feeCollector_; currentDay = endOfDay(block.timestamp); uint256 lastDay = currentDay - 1 days; uint256 currentPrice = twapOracle.getTwap(lastDay); require(currentPrice != 0, "Price not available"); _historicalNavs[lastDay][TRANCHE_M] = UNIT; _historicalNavs[lastDay][TRANCHE_A] = UNIT; _historicalNavs[lastDay][TRANCHE_B] = UNIT; historicalInterestRate[_endOfWeek(lastDay)] = MAX_INTEREST_RATE.min(aprOracle.capture()); fundActivityStartTime = lastDay; exchangeActivityStartTime = lastDay + 30 minutes; activityDelayTimeAfterRebalance = 12 hours; } function initialize( address tokenM_, address tokenA_, address tokenB_, address primaryMarket_ ) external onlyOwner { require(tokenM == address(0) && tokenM_ != address(0), "Already initialized"); tokenM = tokenM_; tokenA = tokenA_; tokenB = tokenB_; _initializeRoles(tokenM_, tokenA_, tokenB_, primaryMarket_); } /// @notice Return weights of Token A and B when splitting Token M. /// @return weightA Weight of Token A /// @return weightB Weight of Token B function trancheWeights() external pure override returns (uint256 weightA, uint256 weightB) { return (WEIGHT_A, WEIGHT_B); } /// @notice UTC time of a day when the fund settles. function settlementTime() external pure returns (uint256) { return SETTLEMENT_TIME; } /// @notice Return end timestamp of the trading day containing a given timestamp. /// /// A trading day starts at UTC time `SETTLEMENT_TIME` of a day (inclusive) /// and ends at the same time of the next day (exclusive). /// @param timestamp The given timestamp /// @return End timestamp of the trading day. function endOfDay(uint256 timestamp) public pure override returns (uint256) { return ((timestamp.add(1 days) - SETTLEMENT_TIME) / 1 days) * 1 days + SETTLEMENT_TIME; } /// @notice Return end timestamp of the trading week containing a given timestamp. /// /// A trading week starts at UTC time `SETTLEMENT_TIME` on a Thursday (inclusive) /// and ends at the same time of the next Thursday (exclusive). /// @param timestamp The given timestamp /// @return End timestamp of the trading week. function endOfWeek(uint256 timestamp) external pure returns (uint256) { return _endOfWeek(timestamp); } /// @notice Return the status of the fund contract. /// @param timestamp Timestamp to assess /// @return True if the fund contract is active function isFundActive(uint256 timestamp) public view override returns (bool) { return timestamp >= fundActivityStartTime; } /// @notice Return the status of a given primary market contract. /// @param primaryMarket The primary market contract address /// @param timestamp Timestamp to assess /// @return True if the primary market contract is active function isPrimaryMarketActive(address primaryMarket, uint256 timestamp) public view override returns (bool) { return isPrimaryMarket(primaryMarket) && timestamp >= fundActivityStartTime && timestamp < currentDay; } /// @notice Return the status of the exchange. Unlike the primary market, exchange is /// anonymous to fund /// @param timestamp Timestamp to assess /// @return True if the exchange contract is active function isExchangeActive(uint256 timestamp) public view override returns (bool) { return (timestamp >= exchangeActivityStartTime && timestamp < (currentDay - 60 minutes)); } /// @notice Total shares of the fund, as if all Token A and B are merged. function getTotalShares() public view override returns (uint256) { return _totalSupplies[TRANCHE_M].add(_totalSupplies[TRANCHE_A]).add(_totalSupplies[TRANCHE_B]); } /// @notice Return the rebalance matrix at a given index. A zero struct is returned /// if `index` is out of bound. /// @param index Rebalance index /// @return A rebalance matrix function getRebalance(uint256 index) external view override returns (Rebalance memory) { return _rebalances[index]; } /// @notice Return timestamp of the transaction triggering the rebalance at a given index. /// Zero is returned if `index` is out of bound. /// @param index Rebalance index /// @return Timestamp of the rebalance function getRebalanceTimestamp(uint256 index) external view override returns (uint256) { return _rebalances[index].timestamp; } /// @notice Return the number of historical rebalances. function getRebalanceSize() external view override returns (uint256) { return _rebalanceSize; } /// @notice Return NAV of Token M, A and B of the given trading day. /// @param day End timestamp of a trading day /// @return NAV of Token M, A and B function historicalNavs(uint256 day) external view override returns ( uint256, uint256, uint256 ) { return ( _historicalNavs[day][TRANCHE_M], _historicalNavs[day][TRANCHE_A], _historicalNavs[day][TRANCHE_B] ); } /// @notice Estimate NAV of all tranches at a given timestamp, considering underlying price /// change, accrued protocol fee and accrued interest since the previous settlement. /// /// The extrapolation uses simple interest instead of daily compound interest in /// calculating protocol fee and Token A's interest. There may be significant error /// in the returned values when `timestamp` is far beyond the last settlement. /// @param timestamp Timestamp to estimate /// @param price Price of the underlying asset (18 decimal places) /// @return Estimated NAV of all tranches function extrapolateNav(uint256 timestamp, uint256 price) external view override returns ( uint256, uint256, uint256 ) { // Find the last settled trading day before the given timestamp. uint256 previousDay = currentDay - 1 days; if (previousDay > timestamp) { previousDay = endOfDay(timestamp) - 1 days; } uint256 previousShares = historicalTotalShares[previousDay]; uint256 navM = _extrapolateNavM(previousDay, previousShares, timestamp, price); uint256 navA = _extrapolateNavA(previousDay, previousShares, timestamp); uint256 navB = calculateNavB(navM, navA); return (navM, navA, navB); } function _extrapolateNavM( uint256 previousDay, uint256 previousShares, uint256 timestamp, uint256 price ) private view returns (uint256) { uint256 navM; if (previousShares == 0) { // The fund is empty. Just return the previous recorded NAV. navM = _historicalNavs[previousDay][TRANCHE_M]; if (navM == 0) { // No NAV is recorded because the given timestamp is before the fund launches. return UNIT; } else { return navM; } } uint256 totalValue = price.mul(historicalUnderlying[previousDay].mul(underlyingDecimalMultiplier)); uint256 accruedFee = totalValue.multiplyDecimal(dailyProtocolFeeRate).mul(timestamp - previousDay).div( 1 days ); navM = (totalValue - accruedFee).div(previousShares); return navM; } function _extrapolateNavA( uint256 previousDay, uint256 previousShares, uint256 timestamp ) private view returns (uint256) { uint256 navA = _historicalNavs[previousDay][TRANCHE_A]; if (previousShares == 0) { // The fund is empty. Just return the previous recorded NAV. if (navA == 0) { // No NAV is recorded because the given timestamp is before the fund launches. return UNIT; } else { return navA; } } uint256 week = _endOfWeek(previousDay); uint256 newNavA = navA .multiplyDecimal( UNIT.sub(dailyProtocolFeeRate.mul(timestamp - previousDay).div(1 days)) ) .multiplyDecimal( UNIT.add(historicalInterestRate[week].mul(timestamp - previousDay).div(1 days)) ); return newNavA > navA ? newNavA : navA; } function calculateNavB(uint256 navM, uint256 navA) public pure override returns (uint256) { // Using unchecked multiplications because they are unlikely to overflow if (navM * WEIGHT_M >= navA * WEIGHT_A) { return (navM * WEIGHT_M - navA * WEIGHT_A) / WEIGHT_B; } else { return 0; } } /// @notice Transform share amounts according to the rebalance at a given index. /// This function performs no bounds checking on the given index. A non-existent /// rebalance transforms anything to a zero vector. /// @param amountM Amount of Token M before the rebalance /// @param amountA Amount of Token A before the rebalance /// @param amountB Amount of Token B before the rebalance /// @param index Rebalance index /// @return newAmountM Amount of Token M after the rebalance /// @return newAmountA Amount of Token A after the rebalance /// @return newAmountB Amount of Token B after the rebalance function doRebalance( uint256 amountM, uint256 amountA, uint256 amountB, uint256 index ) public view override returns ( uint256 newAmountM, uint256 newAmountA, uint256 newAmountB ) { Rebalance storage rebalance = _rebalances[index]; newAmountM = amountM .multiplyDecimal(rebalance.ratioM) .add(amountA.multiplyDecimal(rebalance.ratioA2M)) .add(amountB.multiplyDecimal(rebalance.ratioB2M)); uint256 ratioAB = rebalance.ratioAB; // Gas saver newAmountA = amountA.multiplyDecimal(ratioAB); newAmountB = amountB.multiplyDecimal(ratioAB); } /// @notice Transform share amounts according to rebalances in a given index range, /// This function performs no bounds checking on the given indices. The original amounts /// are returned if `fromIndex` is no less than `toIndex`. A zero vector is returned /// if `toIndex` is greater than the number of existing rebalances. /// @param amountM Amount of Token M before the rebalance /// @param amountA Amount of Token A before the rebalance /// @param amountB Amount of Token B before the rebalance /// @param fromIndex Starting of the rebalance index range, inclusive /// @param toIndex End of the rebalance index range, exclusive /// @return newAmountM Amount of Token M after the rebalance /// @return newAmountA Amount of Token A after the rebalance /// @return newAmountB Amount of Token B after the rebalance function batchRebalance( uint256 amountM, uint256 amountA, uint256 amountB, uint256 fromIndex, uint256 toIndex ) external view override returns ( uint256 newAmountM, uint256 newAmountA, uint256 newAmountB ) { for (uint256 i = fromIndex; i < toIndex; i++) { (amountM, amountA, amountB) = doRebalance(amountM, amountA, amountB, i); } newAmountM = amountM; newAmountA = amountA; newAmountB = amountB; } /// @notice Transform share balance to a given rebalance version, or to the latest version /// if `targetVersion` is zero. /// @param account Account of the balance to rebalance /// @param targetVersion The target rebalance version, or zero for the latest version function refreshBalance(address account, uint256 targetVersion) external override { if (targetVersion > 0) { require(targetVersion <= _rebalanceSize, "Target version out of bound"); } _refreshBalance(account, targetVersion); } /// @notice Transform allowance to a given rebalance version, or to the latest version /// if `targetVersion` is zero. /// @param owner Owner of the allowance to rebalance /// @param spender Spender of the allowance to rebalance /// @param targetVersion The target rebalance version, or zero for the latest version function refreshAllowance( address owner, address spender, uint256 targetVersion ) external override { if (targetVersion > 0) { require(targetVersion <= _rebalanceSize, "Target version out of bound"); } _refreshAllowance(owner, spender, targetVersion); } function shareBalanceOf(uint256 tranche, address account) external view override returns (uint256) { uint256 amountM = _balances[account][TRANCHE_M]; uint256 amountA = _balances[account][TRANCHE_A]; uint256 amountB = _balances[account][TRANCHE_B]; if (tranche == TRANCHE_M) { if (amountM == 0 && amountA == 0 && amountB == 0) return 0; } else if (tranche == TRANCHE_A) { if (amountA == 0) return 0; } else { if (amountB == 0) return 0; } uint256 size = _rebalanceSize; // Gas saver for (uint256 i = _balanceVersions[account]; i < size; i++) { (amountM, amountA, amountB) = doRebalance(amountM, amountA, amountB, i); } if (tranche == TRANCHE_M) { return amountM; } else if (tranche == TRANCHE_A) { return amountA; } else { return amountB; } } /// @notice Return all three share balances transformed to the latest rebalance version. /// @param account Owner of the shares function allShareBalanceOf(address account) external view override returns ( uint256, uint256, uint256 ) { uint256 amountM = _balances[account][TRANCHE_M]; uint256 amountA = _balances[account][TRANCHE_A]; uint256 amountB = _balances[account][TRANCHE_B]; uint256 size = _rebalanceSize; // Gas saver for (uint256 i = _balanceVersions[account]; i < size; i++) { (amountM, amountA, amountB) = doRebalance(amountM, amountA, amountB, i); } return (amountM, amountA, amountB); } function shareBalanceVersion(address account) external view override returns (uint256) { return _balanceVersions[account]; } function shareAllowance( uint256 tranche, address owner, address spender ) external view override returns (uint256) { uint256 allowanceM = _allowances[owner][spender][TRANCHE_M]; uint256 allowanceA = _allowances[owner][spender][TRANCHE_A]; uint256 allowanceB = _allowances[owner][spender][TRANCHE_B]; if (tranche == TRANCHE_M) { if (allowanceM == 0) return 0; } else if (tranche == TRANCHE_A) { if (allowanceA == 0) return 0; } else { if (allowanceB == 0) return 0; } uint256 size = _rebalanceSize; // Gas saver for (uint256 i = _allowanceVersions[owner][spender]; i < size; i++) { (allowanceM, allowanceA, allowanceB) = _rebalanceAllowance( allowanceM, allowanceA, allowanceB, i ); } if (tranche == TRANCHE_M) { return allowanceM; } else if (tranche == TRANCHE_A) { return allowanceA; } else { return allowanceB; } } function shareAllowanceVersion(address owner, address spender) external view override returns (uint256) { return _allowanceVersions[owner][spender]; } function shareTotalSupply(uint256 tranche) external view override returns (uint256) { return _totalSupplies[tranche]; } function mint( uint256 tranche, address account, uint256 amount ) external override onlyPrimaryMarket { _refreshBalance(account, _rebalanceSize); _mint(tranche, account, amount); } function burn( uint256 tranche, address account, uint256 amount ) external override onlyPrimaryMarket { _refreshBalance(account, _rebalanceSize); _burn(tranche, account, amount); } function transfer( uint256 tranche, address sender, address recipient, uint256 amount ) public override onlyShare { require(isFundActive(block.timestamp), "Transfer is inactive"); _refreshBalance(sender, _rebalanceSize); _refreshBalance(recipient, _rebalanceSize); _transfer(tranche, sender, recipient, amount); } function transferFrom( uint256 tranche, address spender, address sender, address recipient, uint256 amount ) external override onlyShare returns (uint256 newAllowance) { transfer(tranche, sender, recipient, amount); _refreshAllowance(sender, spender, _rebalanceSize); newAllowance = _allowances[sender][spender][tranche].sub( amount, "ERC20: transfer amount exceeds allowance" ); _approve(tranche, sender, spender, newAllowance); } function approve( uint256 tranche, address owner, address spender, uint256 amount ) external override onlyShare { _refreshAllowance(owner, spender, _rebalanceSize); _approve(tranche, owner, spender, amount); } function increaseAllowance( uint256 tranche, address sender, address spender, uint256 addedValue ) external override onlyShare returns (uint256 newAllowance) { _refreshAllowance(sender, spender, _rebalanceSize); newAllowance = _allowances[sender][spender][tranche].add(addedValue); _approve(tranche, sender, spender, newAllowance); } function decreaseAllowance( uint256 tranche, address sender, address spender, uint256 subtractedValue ) external override onlyShare returns (uint256 newAllowance) { _refreshAllowance(sender, spender, _rebalanceSize); newAllowance = _allowances[sender][spender][tranche].sub(subtractedValue); _approve(tranche, sender, spender, newAllowance); } function _transfer( uint256 tranche, address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender][tranche] = _balances[sender][tranche].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient][tranche] = _balances[recipient][tranche].add(amount); emit Transfer(tranche, sender, recipient, amount); } function _mint( uint256 tranche, address account, uint256 amount ) private { require(account != address(0), "ERC20: mint to the zero address"); _totalSupplies[tranche] = _totalSupplies[tranche].add(amount); _balances[account][tranche] = _balances[account][tranche].add(amount); emit Transfer(tranche, address(0), account, amount); } function _burn( uint256 tranche, address account, uint256 amount ) private { require(account != address(0), "ERC20: burn from the zero address"); _balances[account][tranche] = _balances[account][tranche].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupplies[tranche] = _totalSupplies[tranche].sub(amount); emit Transfer(tranche, account, address(0), amount); } function _approve( uint256 tranche, address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender][tranche] = amount; emit Approval(tranche, owner, spender, amount); } /// @notice Settle the current trading day. Settlement includes the following changes /// to the fund. /// /// 1. Transfer protocol fee of the day to the fee collector. /// 2. Settle all pending creations and redemptions from all primary markets. /// 3. Calculate NAV of the day and trigger rebalance if necessary. /// 4. Capture new interest rate for Token A. function settle() external nonReentrant { uint256 day = currentDay; uint256 currentWeek = _endOfWeek(day - 1 days); require(block.timestamp >= day, "The current trading day does not end yet"); uint256 price = twapOracle.getTwap(day); require(price != 0, "Underlying price for settlement is not ready yet"); _collectFee(); _settlePrimaryMarkets(day, price); // Calculate NAV uint256 totalShares = getTotalShares(); uint256 underlying = IERC20(tokenUnderlying).balanceOf(address(this)); uint256 navA = _historicalNavs[day - 1 days][TRANCHE_A]; uint256 navM; if (totalShares > 0) { navM = price.mul(underlying.mul(underlyingDecimalMultiplier)).div(totalShares); if (historicalTotalShares[day - 1 days] > 0) { // Update NAV of Token A only when the fund is non-empty both before and after // this settlement uint256 newNavA = navA.multiplyDecimal(UNIT.sub(dailyProtocolFeeRate)).multiplyDecimal( historicalInterestRate[currentWeek].add(UNIT) ); if (navA < newNavA) { navA = newNavA; } } } else { // If the fund is empty, use NAV of Token M in the last day navM = _historicalNavs[day - 1 days][TRANCHE_M]; } uint256 navB = calculateNavB(navM, navA); if (_shouldTriggerRebalance(navA, navB)) { _triggerRebalance(day, navM, navA, navB); navM = UNIT; navA = UNIT; navB = UNIT; totalShares = getTotalShares(); fundActivityStartTime = day + activityDelayTimeAfterRebalance; exchangeActivityStartTime = day + activityDelayTimeAfterRebalance; } else { fundActivityStartTime = day; exchangeActivityStartTime = day + 30 minutes; } if (currentDay == currentWeek) { historicalInterestRate[currentWeek + 1 weeks] = _updateInterestRate(currentWeek); } historicalTotalShares[day] = totalShares; historicalUnderlying[day] = underlying; _historicalNavs[day][TRANCHE_M] = navM; _historicalNavs[day][TRANCHE_A] = navA; _historicalNavs[day][TRANCHE_B] = navB; currentDay = day + 1 days; if (obsoletePrimaryMarkets.length > 0) { for (uint256 i = 0; i < obsoletePrimaryMarkets.length; i++) { _removePrimaryMarket(obsoletePrimaryMarkets[i]); } delete obsoletePrimaryMarkets; } if (newPrimaryMarkets.length > 0) { for (uint256 i = 0; i < newPrimaryMarkets.length; i++) { _addPrimaryMarket(newPrimaryMarkets[i]); } delete newPrimaryMarkets; } emit Settled(day, navM, navA, navB); } function addObsoletePrimaryMarket(address obsoletePrimaryMarket) external onlyOwner { require(isPrimaryMarket(obsoletePrimaryMarket), "The address is not a primary market"); obsoletePrimaryMarkets.push(obsoletePrimaryMarket); } function addNewPrimaryMarket(address newPrimaryMarket) external onlyOwner { require(!isPrimaryMarket(newPrimaryMarket), "The address is already a primary market"); newPrimaryMarkets.push(newPrimaryMarket); } function updateDailyProtocolFeeRate(uint256 newDailyProtocolFeeRate) external onlyOwner { require( newDailyProtocolFeeRate <= MAX_DAILY_PROTOCOL_FEE_RATE, "Exceed max protocol fee rate" ); dailyProtocolFeeRate = newDailyProtocolFeeRate; } function updateTwapOracle(address newTwapOracle) external onlyOwner { twapOracle = ITwapOracle(newTwapOracle); } function updateAprOracle(address newAprOracle) external onlyOwner { aprOracle = IAprOracle(newAprOracle); } function updateBallot(address newBallot) external onlyOwner { ballot = IBallot(newBallot); } function updateFeeCollector(address newFeeCollector) external onlyOwner { feeCollector = newFeeCollector; } function updateActivityDelayTime(uint256 delayTime) external onlyOwner { require( delayTime >= 30 minutes && delayTime <= 12 hours, "Exceed allowed delay time range" ); activityDelayTimeAfterRebalance = delayTime; } /// @dev Transfer protocol fee of the current trading day to the fee collector. /// This function should be called before creation and redemption on the same day /// are settled. function _collectFee() private { uint256 currentUnderlying = IERC20(tokenUnderlying).balanceOf(address(this)); uint256 fee = currentUnderlying.multiplyDecimal(dailyProtocolFeeRate); if (fee > 0) { IERC20(tokenUnderlying).safeTransfer(address(feeCollector), fee); } } /// @dev Settle primary market operations in every PrimaryMarket contract. function _settlePrimaryMarkets(uint256 day, uint256 price) private { uint256 totalShares = getTotalShares(); uint256 underlying = IERC20(tokenUnderlying).balanceOf(address(this)); uint256 prevNavM = _historicalNavs[day - 1 days][TRANCHE_M]; uint256 primaryMarketCount = getPrimaryMarketCount(); for (uint256 i = 0; i < primaryMarketCount; i++) { uint256 price_ = price; // Fix the "stack too deep" error IPrimaryMarket pm = IPrimaryMarket(getPrimaryMarketMember(i)); ( uint256 sharesToMint, uint256 sharesToBurn, uint256 creationUnderlying, uint256 redemptionUnderlying, uint256 fee ) = pm.settle(day, totalShares, underlying, price_, prevNavM); if (sharesToMint > sharesToBurn) { _mint(TRANCHE_M, address(pm), sharesToMint - sharesToBurn); } else if (sharesToBurn > sharesToMint) { _burn(TRANCHE_M, address(pm), sharesToBurn - sharesToMint); } if (creationUnderlying > redemptionUnderlying) { IERC20(tokenUnderlying).safeTransferFrom( address(pm), address(this), creationUnderlying - redemptionUnderlying ); } else if (redemptionUnderlying > creationUnderlying) { IERC20(tokenUnderlying).safeTransfer( address(pm), redemptionUnderlying - creationUnderlying ); } if (fee > 0) { IERC20(tokenUnderlying).safeTransfer(address(feeCollector), fee); } } } /// @dev Check whether a new rebalance should be triggered. Rebalance is triggered if /// NAV of Token B over NAV of Token A is greater than the upper threshold or /// less than the lower threshold. /// @param navA NAV of Token A before the rebalance /// @param navBOrZero NAV of Token B before the rebalance or zero if the NAV is negative /// @return Whether a new rebalance should be triggered function _shouldTriggerRebalance(uint256 navA, uint256 navBOrZero) private view returns (bool) { uint256 bOverA = navBOrZero.divideDecimal(navA); return bOverA < lowerRebalanceThreshold || bOverA > upperRebalanceThreshold; } /// @dev Create a new rebalance that resets NAV of all tranches to 1. Total supplies are /// rebalanced immediately. /// @param day Trading day that triggers this rebalance /// @param navM NAV of Token M before this rebalance /// @param navA NAV of Token A before this rebalance /// @param navBOrZero NAV of Token B before this rebalance or zero if the NAV is negative function _triggerRebalance( uint256 day, uint256 navM, uint256 navA, uint256 navBOrZero ) private { Rebalance memory rebalance = _calculateRebalance(navM, navA, navBOrZero); uint256 oldSize = _rebalanceSize; _rebalances[oldSize] = rebalance; _rebalanceSize = oldSize + 1; emit RebalanceTriggered( oldSize, day, rebalance.ratioM, rebalance.ratioA2M, rebalance.ratioB2M, rebalance.ratioAB ); ( _totalSupplies[TRANCHE_M], _totalSupplies[TRANCHE_A], _totalSupplies[TRANCHE_B] ) = doRebalance( _totalSupplies[TRANCHE_M], _totalSupplies[TRANCHE_A], _totalSupplies[TRANCHE_B], oldSize ); _refreshBalance(address(this), oldSize + 1); } /// @dev Create a new rebalance matrix that resets given NAVs to (1, 1, 1). /// /// Note that NAV of Token B can be negative before the rebalance when the underlying price /// drops dramatically in a single trading day, in which case zero should be passed to /// this function instead of the negative NAV. /// @param navM NAV of Token M before the rebalance /// @param navA NAV of Token A before the rebalance /// @param navBOrZero NAV of Token B before the rebalance or zero if the NAV is negative /// @return The rebalance matrix function _calculateRebalance( uint256 navM, uint256 navA, uint256 navBOrZero ) private view returns (Rebalance memory) { uint256 ratioAB; uint256 ratioA2M; uint256 ratioB2M; if (navBOrZero <= navA) { // Lower rebalance ratioAB = navBOrZero; ratioA2M = ((navM - navBOrZero) * WEIGHT_M) / WEIGHT_A; ratioB2M = 0; } else { // Upper rebalance ratioAB = UNIT; ratioA2M = navA - UNIT; ratioB2M = navBOrZero - UNIT; } return Rebalance({ ratioM: navM, ratioA2M: ratioA2M, ratioB2M: ratioB2M, ratioAB: ratioAB, timestamp: block.timestamp }); } function _updateInterestRate(uint256 week) private returns (uint256) { uint256 baseInterestRate = MAX_INTEREST_RATE.min(aprOracle.capture()); uint256 floatingInterestRate = ballot.count(week).div(365); uint256 rate = baseInterestRate.add(floatingInterestRate); emit InterestRateUpdated(baseInterestRate, floatingInterestRate); return rate; } /// @dev Transform share balance to a given rebalance version, or to the latest version /// if `targetVersion` is zero. This function does no bound check on `targetVersion`. /// @param account Account of the balance to rebalance /// @param targetVersion The target rebalance version, or zero for the latest version function _refreshBalance(address account, uint256 targetVersion) private { if (targetVersion == 0) { targetVersion = _rebalanceSize; } uint256 oldVersion = _balanceVersions[account]; if (oldVersion >= targetVersion) { return; } uint256[TRANCHE_COUNT] storage balanceTuple = _balances[account]; uint256 balanceM = balanceTuple[TRANCHE_M]; uint256 balanceA = balanceTuple[TRANCHE_A]; uint256 balanceB = balanceTuple[TRANCHE_B]; _balanceVersions[account] = targetVersion; if (balanceM == 0 && balanceA == 0 && balanceB == 0) { // Fast path for an empty account return; } for (uint256 i = oldVersion; i < targetVersion; i++) { (balanceM, balanceA, balanceB) = doRebalance(balanceM, balanceA, balanceB, i); } balanceTuple[TRANCHE_M] = balanceM; balanceTuple[TRANCHE_A] = balanceA; balanceTuple[TRANCHE_B] = balanceB; emit BalancesRebalanced(account, targetVersion, balanceM, balanceA, balanceB); } /// @dev Transform allowance to a given rebalance version, or to the latest version /// if `targetVersion` is zero. This function does no bound check on `targetVersion`. /// @param owner Owner of the allowance to rebalance /// @param spender Spender of the allowance to rebalance /// @param targetVersion The target rebalance version, or zero for the latest version function _refreshAllowance( address owner, address spender, uint256 targetVersion ) private { if (targetVersion == 0) { targetVersion = _rebalanceSize; } uint256 oldVersion = _allowanceVersions[owner][spender]; if (oldVersion >= targetVersion) { return; } uint256[TRANCHE_COUNT] storage allowanceTuple = _allowances[owner][spender]; uint256 allowanceM = allowanceTuple[TRANCHE_M]; uint256 allowanceA = allowanceTuple[TRANCHE_A]; uint256 allowanceB = allowanceTuple[TRANCHE_B]; _allowanceVersions[owner][spender] = targetVersion; if (allowanceM == 0 && allowanceA == 0 && allowanceB == 0) { // Fast path for an empty allowance return; } for (uint256 i = oldVersion; i < targetVersion; i++) { (allowanceM, allowanceA, allowanceB) = _rebalanceAllowance( allowanceM, allowanceA, allowanceB, i ); } allowanceTuple[TRANCHE_M] = allowanceM; allowanceTuple[TRANCHE_A] = allowanceA; allowanceTuple[TRANCHE_B] = allowanceB; emit AllowancesRebalanced( owner, spender, targetVersion, allowanceM, allowanceA, allowanceB ); } function _rebalanceAllowance( uint256 allowanceM, uint256 allowanceA, uint256 allowanceB, uint256 index ) private view returns ( uint256 newAllowanceM, uint256 newAllowanceA, uint256 newAllowanceB ) { Rebalance storage rebalance = _rebalances[index]; /// @dev using saturating arithmetic to avoid unconscious overflow revert newAllowanceM = allowanceM.saturatingMultiplyDecimal(rebalance.ratioM); newAllowanceA = allowanceA.saturatingMultiplyDecimal(rebalance.ratioAB); newAllowanceB = allowanceB.saturatingMultiplyDecimal(rebalance.ratioAB); } }
Transfer protocol fee of the current trading day to the fee collector. This function should be called before creation and redemption on the same day are settled.
function _collectFee() private { uint256 currentUnderlying = IERC20(tokenUnderlying).balanceOf(address(this)); uint256 fee = currentUnderlying.multiplyDecimal(dailyProtocolFeeRate); if (fee > 0) { IERC20(tokenUnderlying).safeTransfer(address(feeCollector), fee); } }
12,579,426
// File: contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity ^0.5.0; /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @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. * * _Available since v2.4.0._ */ 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 c = a - b; return c; } /** * @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. * * _Available since v2.4.0._ */ function sub(uint64 a, uint64 b, string memory errorMessage) internal pure returns (uint64) { require(b <= a, errorMessage); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io 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 http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function allowedToCatgorize() public view returns(uint roleId); /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint); } // File: contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io 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 http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMaster { mapping(address => bool) public whitelistedSponsor; function dAppToken() public view returns(address); function isInternal(address _address) public view returns(bool); function getLatestAddress(bytes2 _module) public view returns(address); function isAuthorizedToGovern(address _toCheck) public view returns(bool); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: contracts/external/proxy/Proxy.sol pragma solidity 0.5.7; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () external payable { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); } // File: contracts/external/proxy/UpgradeabilityProxy.sol pragma solidity 0.5.7; /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant IMPLEMENTATION_POSITION = keccak256("org.govblocks.proxy.implementation"); /** * @dev Constructor function */ constructor() public {} /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address impl) { bytes32 position = IMPLEMENTATION_POSITION; assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param _newImplementation address representing the new implementation to be set */ function _setImplementation(address _newImplementation) internal { bytes32 position = IMPLEMENTATION_POSITION; assembly { sstore(position, _newImplementation) } } /** * @dev Upgrades the implementation address * @param _newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address _newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != _newImplementation); _setImplementation(_newImplementation); emit Upgraded(_newImplementation); } } // File: contracts/external/proxy/OwnedUpgradeabilityProxy.sol pragma solidity 0.5.7; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant PROXY_OWNER_POSITION = keccak256("org.govblocks.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param _implementation representing the address of the new implementation to be set. */ function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } /** * @dev Sets the address of the owner */ function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } } // File: contracts/interfaces/IToken.sol pragma solidity 0.5.7; contract IToken { function decimals() external view returns(uint8); /** * @dev Total number of tokens in existence */ function totalSupply() external view returns (uint256); /** * @dev Gets the balance of the specified address. * @param account The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address account) external view returns (uint256); /** * @dev Transfer token for a specified address * @param recipient The address to transfer to. * @param amount The amount to be transferred. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) external returns (bool); /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) external; /** * @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. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Transfer tokens from one address to another * @param sender address The address which you want to send tokens from * @param recipient address The address which you want to transfer to * @param amount uint256 the amount of tokens to be transferred */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // File: contracts/interfaces/IMarket.sol pragma solidity 0.5.7; contract IMarket { enum PredictionStatus { Live, InSettlement, Cooling, InDispute, Settled } struct MarketData { uint64 startTime; uint64 predictionTime; uint64 neutralMinValue; uint64 neutralMaxValue; } struct MarketSettleData { uint64 WinningOption; uint64 settleTime; } MarketSettleData public marketSettleData; MarketData public marketData; function WinningOption() public view returns(uint256); function marketCurrency() public view returns(bytes32); function getMarketFeedData() public view returns(uint8, bytes32, address); function settleMarket() external; function getTotalStakedValueInPLOT() external view returns(uint256); /** * @dev Initialize the market. * @param _startTime The time at which market will create. * @param _predictionTime The time duration of market. * @param _minValue The minimum value of middle option range. * @param _maxValue The maximum value of middle option range. */ function initiate(uint64 _startTime, uint64 _predictionTime, uint64 _minValue, uint64 _maxValue) public payable; /** * @dev Resolve the dispute if wrong value passed at the time of market result declaration. * @param accepted The flag defining that the dispute raised is accepted or not * @param finalResult The final correct value of market currency. */ function resolveDispute(bool accepted, uint256 finalResult) external payable; /** * @dev Gets the market data. * @return _marketCurrency bytes32 representing the currency or stock name of the market. * @return minvalue uint[] memory representing the minimum range of all the options of the market. * @return maxvalue uint[] memory representing the maximum range of all the options of the market. * @return _optionPrice uint[] memory representing the option price of each option ranges of the market. * @return _ethStaked uint[] memory representing the ether staked on each option ranges of the market. * @return _plotStaked uint[] memory representing the plot staked on each option ranges of the market. * @return _predictionType uint representing the type of market. * @return _expireTime uint representing the expire time of the market. * @return _predictionStatus uint representing the status of the market. */ function getData() external view returns ( bytes32 _marketCurrency,uint[] memory minvalue,uint[] memory maxvalue, uint[] memory _optionPrice, uint[] memory _ethStaked, uint[] memory _plotStaked,uint _predictionType, uint _expireTime, uint _predictionStatus ); // /** // * @dev Gets the pending return. // * @param _user The address to specify the return of. // * @return uint representing the pending return amount. // */ // function getPendingReturn(address _user) external view returns(uint[] memory returnAmount, address[] memory _predictionAssets, uint[] memory incentive, address[] memory _incentiveTokens); /** * @dev Claim the return amount of the specified address. * @param _user The address to query the claim return amount of. * @return Flag, if 0:cannot claim, 1: Already Claimed, 2: Claimed */ function claimReturn(address payable _user) public returns(uint256); } // File: contracts/interfaces/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { /** * @dev change master address */ function setMasterAddress() public; } // File: contracts/interfaces/IMarketUtility.sol pragma solidity 0.5.7; contract IMarketUtility { function initialize(address payable[] calldata _addressParams, address _initiater) external; /** * @dev to Set authorized address to update parameters */ function setAuthorizedAddres() public; /** * @dev to update uint parameters in Market Config */ function updateUintParameters(bytes8 code, uint256 value) external; /** * @dev to Update address parameters in Market Config */ function updateAddressParameters(bytes8 code, address payable value) external; /** * @dev Get Parameters required to initiate market * @return Addresses of tokens to be distributed as incentives * @return Cool down time for market * @return Rate * @return Commission percent for predictions with ETH * @return Commission percent for predictions with PLOT **/ function getMarketInitialParams() public view returns(address[] memory, uint , uint, uint, uint); function getAssetPriceUSD(address _currencyAddress) external view returns(uint latestAnswer); function getPriceFeedDecimals(address _priceFeed) public view returns(uint8); function getValueAndMultiplierParameters(address _asset, uint256 _amount) public view returns (uint256, uint256); function update() external; function calculatePredictionValue(uint[] memory params, address asset, address user, address marketFeedAddress, bool _checkMultiplier) public view returns(uint _predictionValue, bool _multiplierApplied); /** * @dev Get basic market details * @return Minimum amount required to predict in market * @return Percentage of users leveraged amount to deduct when placed in wrong prediction * @return Decimal points for prediction positions **/ function getBasicMarketDetails() public view returns ( uint256, uint256, uint256, uint256 ); function getDisputeResolutionParams() public view returns (uint256); function calculateOptionPrice(uint[] memory params, address marketFeedAddress) public view returns(uint _optionPrice); /** * @dev Get price of provided feed address * @param _currencyFeedAddress Feed Address of currency on which market options are based on * @return Current price of the market currency **/ function getSettlemetPrice( address _currencyFeedAddress, uint256 _settleTime ) public view returns (uint256 latestAnswer, uint256 roundId); } // File: contracts/MarketRegistry.sol /* Copyright (C) 2020 PlotX.io 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 http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MarketRegistry is Governed, Iupgradable { using SafeMath for *; enum MarketType { HourlyMarket, DailyMarket, WeeklyMarket } struct MarketTypeData { uint64 predictionTime; uint64 optionRangePerc; } struct MarketCurrency { address marketImplementation; uint8 decimals; } struct MarketCreationData { uint64 initialStartTime; address marketAddress; address penultimateMarket; } struct DisputeStake { uint64 proposalId; address staker; uint256 stakeAmount; uint256 ethDeposited; uint256 tokenDeposited; } struct MarketData { bool isMarket; DisputeStake disputeStakes; } struct UserData { uint256 lastClaimedIndex; uint256 marketsCreated; uint256 totalEthStaked; uint256 totalPlotStaked; address[] marketsParticipated; mapping(address => bool) marketsParticipatedFlag; } uint internal marketCreationIncentive; mapping(address => MarketData) marketData; mapping(address => UserData) userData; mapping(uint256 => mapping(uint256 => MarketCreationData)) public marketCreationData; mapping(uint64 => address) disputeProposalId; address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal marketInitiater; address public tokenController; MarketCurrency[] marketCurrencies; MarketTypeData[] marketTypes; bool public marketCreationPaused; IToken public plotToken; IMarketUtility public marketUtility; IGovernance internal governance; IMaster ms; event MarketQuestion(address indexed marketAdd, bytes32 stockName, uint256 indexed predictionType, uint256 startTime); event PlacePrediction(address indexed user,uint256 value, uint256 predictionPoints, address predictionAsset,uint256 prediction,address indexed marketAdd,uint256 _leverage); event MarketResult(address indexed marketAdd, uint256[] totalReward, uint256 winningOption, uint256 closeValue, uint256 roundId); event Claimed(address indexed marketAdd, address indexed user, uint256[] reward, address[] _predictionAssets, uint256 incentive, address incentiveToken); event MarketTypes(uint256 indexed index, uint64 predictionTime, uint64 optionRangePerc); event MarketCurrencies(uint256 indexed index, address marketImplementation, address feedAddress, bytes32 currencyName); event DisputeRaised(address indexed marketAdd, address raisedBy, uint64 proposalId, uint256 proposedValue); event DisputeResolved(address indexed marketAdd, bool status); /** * @dev Checks if given addres is valid market address. */ function isMarket(address _address) public view returns(bool) { return marketData[_address].isMarket; } function isWhitelistedSponsor(address _address) public view returns(bool) { return ms.whitelistedSponsor(_address); } /** * @dev Initialize the PlotX MarketRegistry. * @param _defaultAddress Address authorized to start initial markets * @param _marketUtility The address of market config. * @param _plotToken The instance of PlotX token. */ function initiate(address _defaultAddress, address _marketUtility, address _plotToken, address payable[] memory _configParams) public { require(address(ms) == msg.sender); marketCreationIncentive = 50 ether; plotToken = IToken(_plotToken); address tcAddress = ms.getLatestAddress("TC"); tokenController = tcAddress; marketUtility = IMarketUtility(_generateProxy(_marketUtility)); marketUtility.initialize(_configParams, _defaultAddress); marketInitiater = _defaultAddress; } /** * @dev Start the initial market. */ function addInitialMarketTypesAndStart(uint64 _marketStartTime, address _ethMarketImplementation, address _btcMarketImplementation) external { require(marketInitiater == msg.sender); require(marketTypes.length == 0); _addNewMarketCurrency(_ethMarketImplementation); _addNewMarketCurrency(_btcMarketImplementation); _addMarket(1 hours, 50); _addMarket(24 hours, 200); _addMarket(7 days, 500); for(uint256 i = 0;i < marketTypes.length; i++) { marketCreationData[i][0].initialStartTime = _marketStartTime; marketCreationData[i][1].initialStartTime = _marketStartTime; createMarket(i, 0); createMarket(i, 1); } } /** * @dev Add new market type. * @param _predictionTime The time duration of market. * @param _marketStartTime The time at which market will create. * @param _optionRangePerc Option range percent of neutral min, max options (raised by 2 decimals) */ function addNewMarketType(uint64 _predictionTime, uint64 _marketStartTime, uint64 _optionRangePerc) external onlyAuthorizedToGovern { require(_marketStartTime > now); uint256 _marketType = marketTypes.length; _addMarket(_predictionTime, _optionRangePerc); for(uint256 j = 0;j < marketCurrencies.length; j++) { marketCreationData[_marketType][j].initialStartTime = _marketStartTime; createMarket(_marketType, j); } } /** * @dev Internal function to add market type * @param _predictionTime The time duration of market. * @param _optionRangePerc Option range percent of neutral min, max options (raised by 2 decimals) */ function _addMarket(uint64 _predictionTime, uint64 _optionRangePerc) internal { uint256 _marketType = marketTypes.length; marketTypes.push(MarketTypeData(_predictionTime, _optionRangePerc)); emit MarketTypes(_marketType, _predictionTime, _optionRangePerc); } /** * @dev Add new market currency. */ function addNewMarketCurrency(address _marketImplementation, uint64 _marketStartTime) external onlyAuthorizedToGovern { uint256 _marketCurrencyIndex = marketCurrencies.length; _addNewMarketCurrency(_marketImplementation); for(uint256 j = 0;j < marketTypes.length; j++) { marketCreationData[j][_marketCurrencyIndex].initialStartTime = _marketStartTime; createMarket(j, _marketCurrencyIndex); } } function _addNewMarketCurrency(address _marketImplementation) internal { uint256 _marketCurrencyIndex = marketCurrencies.length; (, bytes32 _currencyName, address _priceFeed) = IMarket(_marketImplementation).getMarketFeedData(); uint8 _decimals = marketUtility.getPriceFeedDecimals(_priceFeed); marketCurrencies.push(MarketCurrency(_marketImplementation, _decimals)); emit MarketCurrencies(_marketCurrencyIndex, _marketImplementation, _priceFeed, _currencyName); } /** * @dev Update the implementations of the market. */ function updateMarketImplementations(uint256[] calldata _currencyIndexes, address[] calldata _marketImplementations) external onlyAuthorizedToGovern { require(_currencyIndexes.length == _marketImplementations.length); for(uint256 i = 0;i< _currencyIndexes.length; i++) { (, , address _priceFeed) = IMarket(_marketImplementations[i]).getMarketFeedData(); uint8 _decimals = marketUtility.getPriceFeedDecimals(_priceFeed); marketCurrencies[_currencyIndexes[i]] = MarketCurrency(_marketImplementations[i], _decimals); } } /** * @dev Upgrade the implementations of the contract. * @param _proxyAddress the proxy address. * @param _newImplementation Address of new implementation contract */ function upgradeContractImplementation(address payable _proxyAddress, address _newImplementation) external onlyAuthorizedToGovern { require(_newImplementation != address(0)); OwnedUpgradeabilityProxy tempInstance = OwnedUpgradeabilityProxy(_proxyAddress); tempInstance.upgradeTo(_newImplementation); } /** * @dev Changes the master address and update it's instance */ function setMasterAddress() public { OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(address(uint160(address(this)))); require(msg.sender == proxy.proxyOwner(),"Sender is not proxy owner."); ms = IMaster(msg.sender); masterAddress = msg.sender; governance = IGovernance(ms.getLatestAddress("GV")); } /** * @dev Creates the new market. * @param _marketType The type of the market. * @param _marketCurrencyIndex the index of market currency. */ function _createMarket(uint256 _marketType, uint256 _marketCurrencyIndex, uint64 _minValue, uint64 _maxValue, uint64 _marketStartTime, bytes32 _currencyName) internal { require(!marketCreationPaused); MarketTypeData memory _marketTypeData = marketTypes[_marketType]; address payable _market = _generateProxy(marketCurrencies[_marketCurrencyIndex].marketImplementation); marketData[_market].isMarket = true; IMarket(_market).initiate(_marketStartTime, _marketTypeData.predictionTime, _minValue, _maxValue); emit MarketQuestion(_market, _currencyName, _marketType, _marketStartTime); (marketCreationData[_marketType][_marketCurrencyIndex].penultimateMarket, marketCreationData[_marketType][_marketCurrencyIndex].marketAddress) = (marketCreationData[_marketType][_marketCurrencyIndex].marketAddress, _market); } /** * @dev Creates the new market * @param _marketType The type of the market. * @param _marketCurrencyIndex the index of market currency. */ function createMarket(uint256 _marketType, uint256 _marketCurrencyIndex) public payable{ address penultimateMarket = marketCreationData[_marketType][_marketCurrencyIndex].penultimateMarket; if(penultimateMarket != address(0)) { IMarket(penultimateMarket).settleMarket(); } if(marketCreationData[_marketType][_marketCurrencyIndex].marketAddress != address(0)) { (,,,,,,,, uint _status) = getMarketDetails(marketCreationData[_marketType][_marketCurrencyIndex].marketAddress); require(_status >= uint(IMarket.PredictionStatus.InSettlement)); } (uint8 _roundOfToNearest, bytes32 _currencyName, address _priceFeed) = IMarket(marketCurrencies[_marketCurrencyIndex].marketImplementation).getMarketFeedData(); marketUtility.update(); uint64 _marketStartTime = calculateStartTimeForMarket(_marketType, _marketCurrencyIndex); uint64 _optionRangePerc = marketTypes[_marketType].optionRangePerc; uint currentPrice = marketUtility.getAssetPriceUSD(_priceFeed); _optionRangePerc = uint64(currentPrice.mul(_optionRangePerc.div(2)).div(10000)); uint64 _decimals = marketCurrencies[_marketCurrencyIndex].decimals; uint64 _minValue = uint64((ceil(currentPrice.sub(_optionRangePerc).div(_roundOfToNearest), 10**_decimals)).mul(_roundOfToNearest)); uint64 _maxValue = uint64((ceil(currentPrice.add(_optionRangePerc).div(_roundOfToNearest), 10**_decimals)).mul(_roundOfToNearest)); _createMarket(_marketType, _marketCurrencyIndex, _minValue, _maxValue, _marketStartTime, _currencyName); userData[msg.sender].marketsCreated++; } /** * @dev function to reward user for initiating market creation calls */ function claimCreationReward() external { require(userData[msg.sender].marketsCreated > 0); uint256 pendingReward = marketCreationIncentive.mul(userData[msg.sender].marketsCreated); require(plotToken.balanceOf(address(this)) > pendingReward); delete userData[msg.sender].marketsCreated; _transferAsset(address(plotToken), msg.sender, pendingReward); } function calculateStartTimeForMarket(uint256 _marketType, uint256 _marketCurrencyIndex) public view returns(uint64 _marketStartTime) { address previousMarket = marketCreationData[_marketType][_marketCurrencyIndex].marketAddress; if(previousMarket != address(0)) { (_marketStartTime, , , ) = IMarket(previousMarket).marketData(); } else { _marketStartTime = marketCreationData[_marketType][_marketCurrencyIndex].initialStartTime; } uint predictionTime = marketTypes[_marketType].predictionTime; if(now > _marketStartTime.add(predictionTime)) { uint noOfMarketsSkipped = ((now).sub(_marketStartTime)).div(predictionTime); _marketStartTime = uint64(_marketStartTime.add(noOfMarketsSkipped.mul(predictionTime))); } } /** * @dev Updates Flag to pause creation of market. */ function pauseMarketCreation() external onlyAuthorizedToGovern { require(!marketCreationPaused); marketCreationPaused = true; } /** * @dev Updates Flag to resume creation of market. */ function resumeMarketCreation() external onlyAuthorizedToGovern { require(marketCreationPaused); marketCreationPaused = false; } /** * @dev Create proposal if user wants to raise the dispute. * @param proposalTitle The title of proposal created by user. * @param description The description of dispute. * @param solutionHash The ipfs solution hash. * @param action The encoded action for solution. * @param _stakeForDispute The token staked to raise the diospute. * @param _user The address who raises the dispute. */ function createGovernanceProposal(string memory proposalTitle, string memory description, string memory solutionHash, bytes memory action, uint256 _stakeForDispute, address _user, uint256 _ethSentToPool, uint256 _tokenSentToPool, uint256 _proposedValue) public { require(isMarket(msg.sender)); uint64 proposalId = uint64(governance.getProposalLength()); marketData[msg.sender].disputeStakes = DisputeStake(proposalId, _user, _stakeForDispute, _ethSentToPool, _tokenSentToPool); disputeProposalId[proposalId] = msg.sender; governance.createProposalwithSolution(proposalTitle, proposalTitle, description, 10, solutionHash, action); emit DisputeRaised(msg.sender, _user, proposalId, _proposedValue); } /** * @dev Resolve the dispute if wrong value passed at the time of market result declaration. * @param _marketAddress The address specify the market. * @param _result The final result of the market. */ function resolveDispute(address payable _marketAddress, uint256 _result) external onlyAuthorizedToGovern { uint256 ethDepositedInPool = marketData[_marketAddress].disputeStakes.ethDeposited; uint256 plotDepositedInPool = marketData[_marketAddress].disputeStakes.tokenDeposited; uint256 stakedAmount = marketData[_marketAddress].disputeStakes.stakeAmount; address payable staker = address(uint160(marketData[_marketAddress].disputeStakes.staker)); address plotTokenAddress = address(plotToken); _transferAsset(plotTokenAddress, _marketAddress, plotDepositedInPool); IMarket(_marketAddress).resolveDispute.value(ethDepositedInPool)(true, _result); emit DisputeResolved(_marketAddress, true); _transferAsset(plotTokenAddress, staker, stakedAmount); } /** * @dev Burns the tokens of member who raised the dispute, if dispute is rejected. * @param _proposalId Id of dispute resolution proposal */ function burnDisputedProposalTokens(uint _proposalId) external onlyAuthorizedToGovern { address disputedMarket = disputeProposalId[uint64(_proposalId)]; IMarket(disputedMarket).resolveDispute(false, 0); emit DisputeResolved(disputedMarket, false); uint _stakedAmount = marketData[disputedMarket].disputeStakes.stakeAmount; plotToken.burn(_stakedAmount); } /** * @dev Claim the pending return of the market. * @param maxRecords Maximum number of records to claim reward for */ function claimPendingReturn(uint256 maxRecords) external { uint256 i; uint len = userData[msg.sender].marketsParticipated.length; uint lastClaimed = len; uint count; for(i = userData[msg.sender].lastClaimedIndex; i < len && count < maxRecords; i++) { if(IMarket(userData[msg.sender].marketsParticipated[i]).claimReturn(msg.sender) > 0) { count++; } else { if(lastClaimed == len) { lastClaimed = i; } } } if(lastClaimed == len) { lastClaimed = i; } userData[msg.sender].lastClaimedIndex = lastClaimed; } function () external payable { } /** * @dev Transfer `_amount` number of market registry assets contract to `_to` address */ function transferAssets(address _asset, address payable _to, uint _amount) external onlyAuthorizedToGovern { _transferAsset(_asset, _to, _amount); } /** * @dev Transfer the assets to specified address. * @param _asset The asset transfer to the specific address. * @param _recipient The address to transfer the asset of * @param _amount The amount which is transfer. */ function _transferAsset(address _asset, address payable _recipient, uint256 _amount) internal { if(_amount > 0) { if(_asset == ETH_ADDRESS) { _recipient.transfer(_amount); } else { require(IToken(_asset).transfer(_recipient, _amount)); } } } function updateUintParameters(bytes8 code, uint256 value) external onlyAuthorizedToGovern { if(code == "MCRINC") { // Incentive to be distributed to user for market creation marketCreationIncentive = value; } else { marketUtility.updateUintParameters(code, value); } } function updateConfigAddressParameters(bytes8 code, address payable value) external onlyAuthorizedToGovern { marketUtility.updateAddressParameters(code, value); } /** * @dev to generater proxy * @param _contractAddress of the proxy */ function _generateProxy(address _contractAddress) internal returns(address payable) { OwnedUpgradeabilityProxy tempInstance = new OwnedUpgradeabilityProxy(_contractAddress); return address(tempInstance); } /** * @dev Emits the MarketResult event. * @param _totalReward The amount of reward to be distribute. * @param winningOption The winning option of the market. * @param closeValue The closing value of the market currency. */ function callMarketResultEvent(uint256[] calldata _totalReward, uint256 winningOption, uint256 closeValue, uint _roundId) external { require(isMarket(msg.sender)); emit MarketResult(msg.sender, _totalReward, winningOption, closeValue, _roundId); } /** * @dev Emits the PlacePrediction event and sets the user data. * @param _user The address who placed prediction. * @param _value The amount of ether user staked. * @param _predictionPoints The positions user will get. * @param _predictionAsset The prediction assets user will get. * @param _prediction The option range on which user placed prediction. * @param _leverage The leverage selected by user at the time of place prediction. */ function setUserGlobalPredictionData(address _user,uint256 _value, uint256 _predictionPoints, address _predictionAsset, uint256 _prediction, uint256 _leverage) external { require(isMarket(msg.sender)); if(_predictionAsset == ETH_ADDRESS) { userData[_user].totalEthStaked = userData[_user].totalEthStaked.add(_value); } else { userData[_user].totalPlotStaked = userData[_user].totalPlotStaked.add(_value); } if(!userData[_user].marketsParticipatedFlag[msg.sender]) { userData[_user].marketsParticipated.push(msg.sender); userData[_user].marketsParticipatedFlag[msg.sender] = true; } emit PlacePrediction(_user, _value, _predictionPoints, _predictionAsset, _prediction, msg.sender,_leverage); } /** * @dev Emits the claimed event. * @param _user The address who claim their reward. * @param _reward The reward which is claimed by user. * @param predictionAssets The prediction assets of user. * @param incentives The incentives of user. * @param incentiveToken The incentive tokens of user. */ function callClaimedEvent(address _user ,uint[] calldata _reward, address[] calldata predictionAssets, uint incentives, address incentiveToken) external { require(isMarket(msg.sender)); emit Claimed(msg.sender, _user, _reward, predictionAssets, incentives, incentiveToken); } /** * @dev Get uint config parameters */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint256 value) { if(code == "MCRINC") { codeVal = code; value = marketCreationIncentive; } } /** * @dev Gets the market details of the specified address. * @param _marketAdd The market address to query the details of market. * @return _feedsource bytes32 representing the currency or stock name of the market. * @return minvalue uint[] memory representing the minimum range of all the options of the market. * @return maxvalue uint[] memory representing the maximum range of all the options of the market. * @return optionprice uint[] memory representing the option price of each option ranges of the market. * @return _ethStaked uint[] memory representing the ether staked on each option ranges of the market. * @return _plotStaked uint[] memory representing the plot staked on each option ranges of the market. * @return _predictionType uint representing the type of market. * @return _expireTime uint representing the expire time of the market. * @return _predictionStatus uint representing the status of the market. */ function getMarketDetails(address _marketAdd)public view returns (bytes32 _feedsource,uint256[] memory minvalue,uint256[] memory maxvalue, uint256[] memory optionprice,uint256[] memory _ethStaked, uint256[] memory _plotStaked,uint256 _predictionType,uint256 _expireTime, uint256 _predictionStatus){ return IMarket(_marketAdd).getData(); } /** * @dev Get total assets staked by user in PlotX platform * @return _plotStaked Total PLOT staked by user * @return _ethStaked Total ETH staked by user */ function getTotalAssetStakedByUser(address _user) external view returns(uint256 _plotStaked, uint256 _ethStaked) { return (userData[_user].totalPlotStaked, userData[_user].totalEthStaked); } /** * @dev Gets the market details of the specified user address. * @param user The address to query the details of market. * @param fromIndex The index to query the details from. * @param toIndex The index to query the details to * @return _market address[] memory representing the address of the market. * @return _winnigOption uint256[] memory representing the winning option range of the market. */ function getMarketDetailsUser(address user, uint256 fromIndex, uint256 toIndex) external view returns (address[] memory _market, uint256[] memory _winnigOption){ uint256 totalMarketParticipated = userData[user].marketsParticipated.length; if(totalMarketParticipated > 0 && fromIndex < totalMarketParticipated) { uint256 _toIndex = toIndex; if(_toIndex >= totalMarketParticipated) { _toIndex = totalMarketParticipated - 1; } _market = new address[](_toIndex.sub(fromIndex).add(1)); _winnigOption = new uint256[](_toIndex.sub(fromIndex).add(1)); for(uint256 i = fromIndex; i <= _toIndex; i++) { _market[i] = userData[user].marketsParticipated[i]; (_winnigOption[i], ) = IMarket(_market[i]).marketSettleData(); } } } /** * @dev Gets the addresses of open markets. * @return _openMarkets address[] memory representing the open market addresses. * @return _marketTypes uint256[] memory representing the open market types. */ function getOpenMarkets() external view returns(address[] memory _openMarkets, uint256[] memory _marketTypes, bytes32[] memory _marketCurrencies) { uint256 count = 0; uint256 marketTypeLength = marketTypes.length; uint256 marketCurrencyLength = marketCurrencies.length; _openMarkets = new address[]((marketTypeLength).mul(marketCurrencyLength)); _marketTypes = new uint256[]((marketTypeLength).mul(marketCurrencyLength)); _marketCurrencies = new bytes32[]((marketTypeLength).mul(marketCurrencyLength)); for(uint256 i = 0; i< marketTypeLength; i++) { for(uint256 j = 0; j< marketCurrencyLength; j++) { _openMarkets[count] = marketCreationData[i][j].marketAddress; _marketTypes[count] = i; _marketCurrencies[count] = IMarket(marketCurrencies[j].marketImplementation).marketCurrency(); count++; } } } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { return ((a + m - 1) / m) * m; } // /** // * @dev Calculates the user pending return amount. // * @param _user The address to query the pending return amount of. // * @return pendingReturn uint256 representing the pending return amount of user. // * @return incentive uint256 representing the incentive. // */ // function calculateUserPendingReturn(address _user) external view returns(uint[] memory returnAmount, address[] memory _predictionAssets, uint[] memory incentive, address[] memory _incentiveTokens) { // uint256 _return; // uint256 _incentive; // for(uint256 i = lastClaimedIndex[_user]; i < marketsParticipated[_user].length; i++) { // // pendingReturn = pendingReturn.add(marketsParticipated[_user][i].call(abi.encodeWithSignature("getPendingReturn(uint256)", _user))); // (_return, _incentive) = IMarket(marketsParticipated[_user][i]).getPendingReturn(_user); // pendingReturn = pendingReturn.add(_return); // incentive = incentive.add(_incentive); // } // } }
Updates Flag to pause creation of market./
function pauseMarketCreation() external onlyAuthorizedToGovern { require(!marketCreationPaused); marketCreationPaused = true; }
10,840,457